12 pthread_mutex_t mutex;
14 friend class Condition;
15 Mutex() { pthread_mutex_init(&mutex, 0); }
16 ~Mutex() { pthread_mutex_destroy(&mutex); }
17 int lock() { return pthread_mutex_lock(&mutex); }
18 int trylock() { return pthread_mutex_trylock(&mutex); }
19 int unlock() { return pthread_mutex_unlock(&mutex); }
20 void reset() { pthread_mutex_destroy(&mutex); pthread_mutex_init(&mutex,0); }
23 class Condition : public Mutex {
29 Mutex::lock(); while(v <= 0) pthread_cond_wait(&cond, &mutex);
30 --v; Mutex::unlock(); return 0;
32 void unlock() { Mutex::lock(); ++v; pthread_cond_signal(&cond); Mutex::unlock(); }
33 Condition(int iv=1) : init_v(iv) {
34 v = init_v; pthread_cond_init(&cond, NULL);
36 ~Condition() { pthread_cond_destroy(&cond); }
38 pthread_cond_destroy(&cond); pthread_cond_init(&cond, NULL);
39 Mutex::reset(); v = 1;
46 pthread_t owner_tid, tid;
48 virtual void run() = 0;
49 static void *proc(void *t) { ((Thread*)t)->run(); return 0; }
50 pthread_t owner() { return owner_tid; }
51 pthread_t self() { return tid; }
52 int running() { return active; }
54 if( started ) { started = 0; pthread_cancel(tid); }
59 pthread_create(&tid, 0, proc,(void*)this);
61 void join() { if( active ) { pthread_join(tid, 0); active = 0; } }
62 void pause() { pthread_kill(tid, SIGSTOP); }
63 void resume() { pthread_kill(tid, SIGCONT); }
64 Thread() { started = active = 0; owner_tid = pthread_self(); }
71 class thread : public Thread {
75 thread() { done = 0; ready.lock(); start(); }
78 virtual void Proc () = 0;
79 void run() { while( !done ) { ready.lock(); if( !done ) Proc(); } }
80 void Run() { ready.unlock(); }
81 void Kill() { done = 1; Run(); join(); }
84 class Lock : public Mutex {};
86 static inline void yield() { pthread_yield(); }