|
| 1 | +// |
| 2 | +// Created by shen on 16-9-16. |
| 3 | +// |
| 4 | +#include "Thread_base_object.h" |
| 5 | +#include <functional> |
| 6 | +#ifndef EFFECTIVECPP_THREAD_BASE_OBJECT_TEST_H |
| 7 | +#define EFFECTIVECPP_THREAD_BASE_OBJECT_TEST_H |
| 8 | + |
| 9 | + |
| 10 | +Thread::Thread(const ThreadFunc &func) : func_(func), autodelete_(false) { |
| 11 | + cout << "thread(),"; |
| 12 | + printf(" pid= %x\n", pthread_self()); |
| 13 | +}; |
| 14 | + |
| 15 | +Thread::~Thread() { |
| 16 | + cout << "~thread(),"; |
| 17 | + printf(" pid= %x\n", pthread_self()); |
| 18 | +} |
| 19 | + |
| 20 | +void *Thread::Thread_routine(void *arg) { |
| 21 | + Thread *thread = static_cast<Thread *>(arg); |
| 22 | + thread->Run(); |
| 23 | + cout << "Thread_routine pid= " << pthread_self() << endl; |
| 24 | + if (thread->autodelete_) delete thread; |
| 25 | + return NULL; |
| 26 | +} |
| 27 | + |
| 28 | +void Thread::Run() { func_(); } |
| 29 | + |
| 30 | +void Thread::SetAutodelete(bool autodelete) { |
| 31 | + autodelete_ = autodelete; |
| 32 | +}; |
| 33 | + |
| 34 | +void Thread::Start() { |
| 35 | + cout << "threadid = " << threadId_ << endl; |
| 36 | + pthread_create(&threadId_, nullptr, Thread_routine, this); |
| 37 | +} |
| 38 | + |
| 39 | +void Thread::Join() { |
| 40 | + pthread_join(threadId_, NULL); |
| 41 | +} |
| 42 | + |
| 43 | +void ThreadFunc1() { |
| 44 | + cout << "func...\n"; |
| 45 | +} |
| 46 | + |
| 47 | +void ThreadFunc2(int count) { |
| 48 | + while (count-- >= 0) { |
| 49 | + cout << " func2..." << count << endl; |
| 50 | + sleep(1); |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | + |
| 55 | +class Foo { |
| 56 | +public: |
| 57 | + Foo(int count) : count_(count) { cout << "Foo()...\n"; } |
| 58 | + |
| 59 | + void MemberFun() { |
| 60 | + while (count_-- >= 0) { |
| 61 | + cout << " func3..." << count_ << endl; |
| 62 | + sleep(1); |
| 63 | + } |
| 64 | + } |
| 65 | + ~Foo(){cout<<"~Foo...\n";} |
| 66 | + |
| 67 | +private: |
| 68 | + int count_; |
| 69 | +}; |
| 70 | + |
| 71 | +namespace Thread_baseon_object { |
| 72 | + void f() { |
| 73 | + Thread t1(ThreadFunc1); |
| 74 | + t1.Start(); |
| 75 | + //基于对象的编程思想 |
| 76 | + Thread t2(bind(ThreadFunc2, 3)); |
| 77 | + t2.Start(); |
| 78 | + t1.Join(); |
| 79 | + t2.Join(); |
| 80 | + cout<<"---\n"; |
| 81 | + Foo foo(3); |
| 82 | + Thread t3(boost::bind(&Foo::MemberFun,&foo)); |
| 83 | + t3.Start(); |
| 84 | + t3.Join(); |
| 85 | + } |
| 86 | +} |
| 87 | +#endif //EFFECTIVECPP_THREAD_BASE_OBJECT_TEST_H |
0 commit comments