Playing with boost threads and unit test
[metaproxy-moved-to-github.git] / src / test_boost_threads.cpp
1
2 #include <boost/thread/mutex.hpp>
3 #include <boost/thread/thread.hpp>
4 #include <list>
5 #include <iostream>
6
7 boost::mutex io_mutex; // The iostreams are not guaranteed to be thread-safe!
8
9 class counter
10 {
11    public:
12       counter() : count(0) { }
13       
14       int increment() {
15          boost::mutex::scoped_lock scoped_lock(mutex);
16          return ++count;
17       }
18       
19    private:
20       boost::mutex mutex;
21       int count;
22 };
23
24
25 counter c;
26
27 void change_count()
28 {
29    int i = c.increment();
30    boost::mutex::scoped_lock scoped_lock(io_mutex);
31    std::cout << "count == " << i << std::endl;
32 }
33
34
35 class worker {
36 public:
37     void operator() (void) {
38         int i = c.increment();
39         
40         i = c.increment();
41         
42         i = c.increment();
43         boost::mutex::scoped_lock scoped_lock(io_mutex);
44         std::cout << "count == " << i << std::endl;
45     }
46     virtual ~worker() { std::cout << "destroyed\n"; }
47 };
48
49
50
51 int main(int, char*[])
52 {
53    try 
54    {
55       const int num_threads = 4;
56       boost::thread_group thrds;
57       
58       std::list<boost::thread *> thread_list;
59       
60       for (int i=0; i < num_threads; ++i)
61       {
62           // thrds.create_thread(&change_count);
63           worker *w = new worker;
64
65           boost::thread *thr = new boost::thread(*w);
66
67           thrds.add_thread(thr);
68
69           thread_list.push_back(thr);
70       }
71       
72       thrds.join_all();
73 #if 0
74       std::list<boost::thread *>::iterator it;
75       for (it = thread_list.begin(); it != thread_list.end(); it++)
76       {
77           delete *it;
78           *it = 0;
79       }
80 #endif
81    }
82    catch (std::exception &e) 
83    {
84       std::cout << e.what() << "\n";
85       exit(1);
86    }
87    exit(0);
88 }
89
90 /*
91  * Local variables:
92  * c-basic-offset: 4
93  * indent-tabs-mode: nil
94  * End:
95  * vim: shiftwidth=4 tabstop=8 expandtab
96  */