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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| #include <muduo/base/CountDownLatch.h> #include <muduo/base/Thread.h>
#include <boost/bind.hpp> #include <boost/ptr_container/ptr_vector.hpp> #include <string> #include <stdio.h>
using namespace muduo;
class Test { public: Test(int numThreads) : latch_(1), threads_(numThreads) { for (int i = 0; i < numThreads; ++i) { char name[32]; snprintf(name, sizeof name, "work thread %d", i); threads_.push_back(new muduo::Thread( boost::bind(&Test::threadFunc, this), muduo::string(name))); } for_each(threads_.begin(), threads_.end(), boost::bind(&Thread::start, _1)); } void run() { latch_.countDown(); }
void joinAll() { for_each(threads_.begin(), threads_.end(), boost::bind(&Thread::join, _1)); }
private: void threadFunc() { latch_.wait(); printf("tid=%d, %s started\n", CurrentThread::tid(), CurrentThread::name());
printf("tid=%d, %s stopped\n", CurrentThread::tid(), CurrentThread::name()); } CountDownLatch latch_; boost::ptr_vector<Thread> threads_; };
int main() { printf("pid=%d, tid=%d\n", ::getpid(), CurrentThread::tid()); Test t(3); sleep(3); printf("pid=%d, tid=%d %s running ...\n", ::getpid(), CurrentThread::tid(), CurrentThread::name()); t.run(); t.joinAll();
printf("number of created threads %d\n", Thread::numCreated()); }
|