1 #include <boost/thread.hpp>
2 #include <boost/thread/mutex.hpp>
3 #include <boost/date_time/posix_time/posix_time.hpp>
4 #include <list>
5
6
7 struct Task
8 {
9 std::string str;
10 };
11
12 class QueueTest
13 {
14 public:
15 QueueTest(void)
16 {
17 }
18 ~QueueTest(void)
19 {
20 }
21
22 public:
23 void Put(const Task& item)
24 {
25 boost::mutex::scoped_lock lock(m_mutex);
26 m_list.push_back(item);
27 m_condGet.notify_one();
28 }
29 void Get(Task& item)
30 {
31 boost::mutex::scoped_lock lock(m_mutex);
32 while (IsEmpty())
33 {
34 m_condGet.wait(lock);
35 }
36 item = m_list.front();
37 m_list.pop_front();
38 }
39
40 private:
41 bool IsEmpty()
42 {
43 return m_list.empty();
44 }
45
46 private:
47 std::list<Task> m_list;
48
49 boost::mutex m_mutex;
50 boost::condition_variable_any m_condGet;
51 };
52
53 QueueTest test;
54
55 void ThreadFun1()
56 {
57 std::cout<<"thread1 run "<<std::endl;
58 Task task;
59 task.str = "ThreadFun1";
60 test.Put(task);
61
62 }
63
64 void ThreadFun2()
65 {
66 Task task;
67 task.str = "ThreadFun2";
68 test.Put(task);
69 }
70
71 void ThreadFun3()
72 {
73 while(true)
74 {
75 Task task;
76 test.Get(task);
77 std::cout<<task.str<<std::endl;
78 }
79 }
80
81 void ThreadFun4()
82 {
83 Task task;
84 task.str = "ThreadFun4";
85 test.Put(task);
86 }
87
88
89 int _tmain(int argc, _TCHAR* argv[])
90 {
91 boost::thread thread1(&ThreadFun1);
92 boost::thread thread2(&ThreadFun2);
93 boost::thread thread3(&ThreadFun3);
94 boost::thread thread4(&ThreadFun4);
95
96 system("pause");
97 return 0;
98 }