Add code to test join of single threads or groups
[metaproxy-moved-to-github.git] / src / test_boost_threads.cpp
1
2 #include <boost/thread/mutex.hpp>
3 #include <boost/thread/thread.hpp>
4
5 #define BOOST_AUTO_TEST_MAIN
6 #include <boost/test/auto_unit_test.hpp>
7
8 #include <list>
9 #include <iostream>
10
11 class counter
12 {
13    public:
14       counter() : count(0) { }
15       
16     int increment() {
17         boost::mutex::scoped_lock scoped_lock(mutex);
18         return ++count;
19     }
20     
21 private:
22     boost::mutex mutex;
23     int count;
24 };
25
26
27 counter c;
28
29 class worker {
30 public:
31     void operator() (void) {
32         c.increment();
33     }
34 };
35
36 #define USE_GROUP 1
37
38
39 BOOST_AUTO_TEST_CASE( thread_group )
40 {
41     try 
42     {
43         const int num_threads = 4;
44         boost::thread_group thrds;
45         
46         for (int i=0; i < num_threads; ++i)
47         {
48             worker w;
49             thrds.add_thread(new boost::thread(w));
50         }
51         thrds.join_all();
52     }
53     catch (...) 
54     {
55         BOOST_CHECK(false);
56     }
57     BOOST_CHECK(c.increment() == 5);
58 }
59
60
61 BOOST_AUTO_TEST_CASE( thread_list )
62 {
63     try 
64     {
65         const int num_threads = 4;
66         std::list<boost::thread *> thread_list;
67         
68         for (int i=0; i < num_threads; ++i)
69         {
70             worker w;
71             thread_list.push_back(new boost::thread(w));
72         }
73         std::list<boost::thread *>::iterator it;
74         for (it = thread_list.begin(); it != thread_list.end(); it++)
75         {
76             (*it)->join();
77             delete *it;
78         }
79
80     }
81     catch (...) 
82     {
83         BOOST_CHECK(false);
84     }
85     BOOST_CHECK(c.increment() == 10);
86 }
87
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  */