Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
Tags
- hbase
- Python
- management
- leadership
- agile
- QT
- programming_book
- web
- MySQL
- psychology
- ubuntu
- Linux
- django
- Java
- RFID
- Software Engineering
- comic agile
- UK
- France
- program
- Programming
- erlang
- Spain
- Book review
- hadoop
- Italy
- Kuala Lumpur
- history
- Malaysia
- Book
Archives
- Today
- Total
C++ thread library 본문
출처: http://yesarang.tistory.com/70
// Runnable.h #ifndef _RUNNABLE_H #define _RUNNABLE_H class Runnable { public: virtual void Run() = 0; }; #endif // Thread.h #ifndef _THREAD_H #define _THREAD_H #include "Runnable.h" class Thread: public Runnable { public: Thread(); Thread(Runnable* pRunnable); void Start(); void Wait(); virtual void Run(); private: pthread_t _thread; Runnable* _runnable; static void* Main(void* pInst); }; #endif // Thread.cpp #include <iostream> #include <pthread.h> #include "Runnable.h" #include "Thread.h" using namespace std; Thread::Thread(): _thread(0), _runnable(0) { } Thread::Thread(Runnable* pRunnable): _thread(0),_runnable(pRunnable) { } void Thread::Start() { cout << "Thread::Start() called" << endl; // register Main() class method as pthred's callback int nr = pthread_create(&_thread, NULL, &Thread::Main, this); } void Thread::Wait() { cout << "Thread::Wait() called" << endl; void* pData; int nr = pthread_join(_thread, &pData); } void Thread::Run() { if ( _runnable != 0 ) { cout << "Thread::Run(): calling runnable" << endl; _runnable->Run(); } } void* Thread::Main(void* pInst) { cout << "Thread::Main(): called" << endl; Thread* pt = static_cast<Thread*>(pInst); pt->Run(); } // cppthread.cpp #include <iostream> #include <unistd.h> #include "Runnable.h" #include "Thread.h" using namespace std; class CountUpto: public Runnable { public: CountUpto(int n = 10): _count(n) {} virtual void Run() { cout << "CountUpto: Starts to run" << endl; int i = 1; do { cout << "CountUpto::Run(): " << i++ << endl; sleep(1); } while ( --_count); } private: int _count; }; class TestThread: public Thread { public: virtual void Run() { cout << "TestThread::Run() called" << endl; int i = 5; do { sleep(1); cout << "TestThread::Run(): " << i << endl; } while ( --i ); } }; int main(void) { Thread* pt1 = new TestThread(); Thread* pt2 = new Thread(new CountUpto(20)); pt1->Start(), pt2->Start(); pt1->Wait(), pt2->Wait(); }
Comments