1#include "../Mutex.h" 2#include "../Thread.h" 3#include <set> 4#include <stdio.h> 5 6class Request; 7 8class Inventory 9{ 10 public: 11 void add(Request* req) 12 { 13 muduo::MutexLockGuard lock(mutex_); 14 requests_.insert(req); 15 } 16 17 void remove(Request* req) __attribute__ ((noinline)) 18 { 19 muduo::MutexLockGuard lock(mutex_); 20 requests_.erase(req); 21 } 22 23 void printAll() const; 24 25 private: 26 mutable muduo::MutexLock mutex_; 27 std::set<Request*> requests_; 28}; 29 30Inventory g_inventory; 31 32class Request 33{ 34 public: 35 void process() // __attribute__ ((noinline)) 36 { 37 muduo::MutexLockGuard lock(mutex_); 38 g_inventory.add(this); 39 // ... 40 } 41 42 ~Request() __attribute__ ((noinline)) 43 { 44 muduo::MutexLockGuard lock(mutex_); 45 sleep(1); 46 g_inventory.remove(this); 47 } 48 49 void print() const __attribute__ ((noinline)) 50 { 51 muduo::MutexLockGuard lock(mutex_); 52 // ... 53 } 54 55 private: 56 mutable muduo::MutexLock mutex_; 57}; 58 59void Inventory::printAll() const 60{ 61 muduo::MutexLockGuard lock(mutex_); 62 sleep(1); 63 for (std::set<Request*>::const_iterator it = requests_.begin(); 64 it != requests_.end(); 65 ++it) 66 { 67 (*it)->print(); 68 } 69 printf("Inventory::printAll() unlocked\n"); 70} 71 72/* 73void Inventory::printAll() const 74{ 75 std::set<Request*> requests 76 { 77 muduo::MutexLockGuard lock(mutex_); 78 requests = requests_; 79 } 80 for (std::set<Request*>::const_iterator it = requests.begin(); 81 it != requests.end(); 82 ++it) 83 { 84 (*it)->print(); 85 } 86} 87*/ 88 89void threadFunc() 90{ 91 Request* req = new Request; 92 req->process(); 93 delete req; 94} 95 96int main() 97{ 98 muduo::Thread thread(threadFunc); 99 thread.start(); 100 usleep(500 * 1000); 101 g_inventory.printAll(); 102 thread.join(); 103} 104