#include #include #include #include #include using std::vector; using std::string; /** * Abstract Thread */ class Thread { public: Thread(){} virtual ~Thread(){} virtual void start(); virtual void join(); virtual pthread_t get_id() const {return thread_handle;} protected: virtual void run() = 0; friend void* thread_ftn(void* arg); pthread_t thread_handle; private: Thread(const Thread& src); Thread& operator=(const Thread& rhs); }; /** * standard thread function */ void* thread_ftn(void* arg) { Thread* t = static_cast(arg); t->run(); return NULL; } void Thread::start() { pthread_create( &thread_handle, NULL, // default attributes thread_ftn, (void *)this); } void Thread::join() { pthread_join(thread_handle, NULL); } /** * some mutex class */ class MutexClass { public: MutexClass(); virtual ~MutexClass(); virtual void lock_mutex(); virtual void unlock_mutex(); protected: pthread_mutex_t mutex; }; MutexClass::MutexClass() { pthread_mutex_init(&mutex, NULL); } MutexClass::~MutexClass() { pthread_mutex_destroy(&mutex); } void MutexClass::lock_mutex() { pthread_mutex_lock(&mutex); } void MutexClass::unlock_mutex() { pthread_mutex_unlock(&mutex); } /** * global mutex object */ MutexClass mut; /** * shared buffer */ vector buffer; /** * My Thread implementation of Thread */ class Producer : public Thread { protected: virtual void run(); }; /** * His Thread implemenation of Thread */ class Consumer : public Thread { protected: virtual void run(); }; void Producer::run() { mut.lock_mutex(); buffer.push_back("Hello from Producer\n"); mut.unlock_mutex(); } void Consumer::run() { int done = 0; while(!done) { mut.lock_mutex(); if(buffer.size() > 0) { std::cout << "got msg: " << buffer.front() << "\n"; done = 1; } mut.unlock_mutex(); } } int main() { Producer prod; Consumer cons; cons.start(); sleep(1); prod.start(); prod.join(); cons.join(); return 0; }