1#include "../BoundedBlockingQueue.h" 2#include "../CountDownLatch.h" 3#include "../Thread.h" 4 5#include <boost/bind.hpp> 6#include <boost/ptr_container/ptr_vector.hpp> 7#include <string> 8#include <stdio.h> 9 10class Test 11{ 12 public: 13 Test(int numThreads) 14 : queue_(20), 15 latch_(numThreads), 16 threads_(numThreads) 17 { 18 for (int i = 0; i < numThreads; ++i) 19 { 20 char name[32]; 21 snprintf(name, sizeof name, "work thread %d", i); 22 threads_.push_back(new muduo::Thread( 23 boost::bind(&Test::threadFunc, this), std::string(name))); 24 } 25 for_each(threads_.begin(), threads_.end(), boost::bind(&muduo::Thread::start, _1)); 26 } 27 28 void run(int times) 29 { 30 printf("waiting for count down latch\n"); 31 latch_.wait(); 32 printf("all threads started\n"); 33 for (int i = 0; i < times; ++i) 34 { 35 char buf[32]; 36 snprintf(buf, sizeof buf, "hello %d", i); 37 queue_.put(buf); 38 printf("tid=%d, put data = %s, size = %zd\n", muduo::CurrentThread::tid(), buf, queue_.size()); 39 } 40 } 41 42 void joinAll() 43 { 44 for (size_t i = 0; i < threads_.size(); ++i) 45 { 46 queue_.put("stop"); 47 } 48 49 for_each(threads_.begin(), threads_.end(), boost::bind(&muduo::Thread::join, _1)); 50 } 51 52 private: 53 54 void threadFunc() 55 { 56 printf("tid=%d, %s started\n", 57 muduo::CurrentThread::tid(), 58 muduo::CurrentThread::name()); 59 60 latch_.countDown(); 61 bool running = true; 62 while (running) 63 { 64 std::string d(queue_.take()); 65 printf("tid=%d, get data = %s, size = %zd\n", muduo::CurrentThread::tid(), d.c_str(), queue_.size()); 66 running = (d != "stop"); 67 } 68 69 printf("tid=%d, %s stopped\n", 70 muduo::CurrentThread::tid(), 71 muduo::CurrentThread::name()); 72 } 73 74 muduo::BoundedBlockingQueue<std::string> queue_; 75 muduo::CountDownLatch latch_; 76 boost::ptr_vector<muduo::Thread> threads_; 77}; 78 79int main() 80{ 81 printf("pid=%d, tid=%d\n", ::getpid(), muduo::CurrentThread::tid()); 82 Test t(5); 83 t.run(100); 84 t.joinAll(); 85 86 printf("number of created threads %d\n", muduo::Thread::numCreated()); 87} 88