2 // Refer to http://www.cscene.org for detailed docs.
4 // Copyright (c) 1998 by Juergen Hermann
6 // To make things easy, we put all code in one file.
7 // Large parts of this should go to thread.hpp/cpp in real real life.
17 ///////////////////////////////////////////////////////////////////////
19 ///////////////////////////////////////////////////////////////////////
21 inline int randrange(int lo, int hi)
23 return rand() / (RAND_MAX / (hi - lo + 1)) + lo;
27 ///////////////////////////////////////////////////////////////////////
28 // A thread base class
29 ///////////////////////////////////////////////////////////////////////
35 pthread_t get_thread() const { return thread; }
39 virtual void code() = 0;
45 static void* dispatch(void* thread_obj);
57 // Don't start two threads on the same object
60 // Create an OS thread, using the static callback
61 assert(!pthread_create(&thread, NULL, Thread::dispatch, static_cast<void*>(this)));
62 pthread_detach(thread);
67 void* Thread::dispatch(void* thread_obj)
69 // Call the actual OO thread code
70 static_cast<Thread*>(thread_obj)->code();
72 // After code() returns, kill the thread object
73 delete static_cast<Thread*>(thread_obj);
79 ///////////////////////////////////////////////////////////////////////
80 // An example thread class
81 ///////////////////////////////////////////////////////////////////////
83 class Dice : private Thread {
85 static void Dice::create(const char* dicename);
86 //static CRITICAL_SECTION sync;
89 Dice(const char* dicename) : name(dicename) {}
96 //CRITICAL_SECTION Dice::sync;
99 void Dice::create(const char* dicename)
101 (new Dice(dicename))->run();
107 //EnterCriticalSection(&sync);
108 std::cout << "Started thread #" << static_cast<unsigned long>(get_thread())
109 << " for " << name << std::endl;
110 //LeaveCriticalSection(&sync);
112 srand(time(0) * get_thread());
115 int val = randrange(1, 6);
117 //EnterCriticalSection(&sync);
118 std::cout << name << " rolled " << val << std::endl;
119 //LeaveCriticalSection(&sync);
121 sleep(randrange(0, 1)); // wait up to 1 sec
126 ///////////////////////////////////////////////////////////////////////
128 ///////////////////////////////////////////////////////////////////////
132 //InitializeCriticalSection(&Dice::sync);
134 Dice::create("dice1");
135 Dice::create("dice2");
137 sleep(10); // roll dice for 10 seconds
139 return 0; // cleanup? what's cleanup?