程序中几个线程一起往控制台写入log_info,但是可以很清楚的看到begin or write_process不会同时连续的出现,而且在begin of write_process和end of write_process之间肯定不会出现begin of read_process或者end of read_process。但是begin of read_process却会在控制台上连续出现,这说明在同一时刻只有一个write_prcess在运行,但是wrte_process没有运行的时候,会有多个read_process并发运行。
1 #include <iostream>
2
3 #include <boost/thread/thread.hpp>
4 #include <boost/thread/shared_mutex.hpp>
5
6 using namespace std;
7 using namespace boost;
8
9 boost::shared_mutex shr_mutex;
10
11 /// 这个是辅助类,能够保证log_info被完整的输出
12 class safe_log {
13 public:
14 static void log(const std::string& log_info) {
15 boost::mutex::scoped_lock lock(log_mutex);
16 cout << log_info << endl;
17 }
18
19 private:
20 static boost::mutex log_mutex;
21 };
22
23 boost::mutex safe_log::log_mutex;
24
25 void write_process() {
26 shr_mutex.lock();
27 safe_log::log("begin of write_process");
28 safe_log::log("end of write_process");
29 shr_mutex.unlock();
30 }
31
32 void read_process() {
33 shr_mutex.lock_shared();
34 safe_log::log("begin of read_process");
35 safe_log::log("end of read_process");
36 shr_mutex.unlock_shared();
37 }
38
39 int main() {
40
41 thread_group threads;
42 for (int i = 0; i < 10; ++ i) {
43 threads.create_thread(&write_process);
44 threads.create_thread(&read_process);
45 }
46
47 threads.join_all();
48
49 ::system("PAUSE");
50
51 return 0;
52 }
posted on 2009-01-21 13:58
许海斌 阅读(2649)
评论(0) 编辑 收藏 引用