GPL v2.
[metaproxy-moved-to-github.git] / src / test_boost_threads.cpp
1 /* $Id: test_boost_threads.cpp,v 1.10 2007-05-09 21:23:09 adam Exp $
2    Copyright (c) 2005-2007, Index Data.
3
4 This file is part of Metaproxy.
5
6 Metaproxy is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
9 version.
10
11 Metaproxy is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Metaproxy; see the file LICENSE.  If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA.
20  */
21
22 #include "config.hpp"
23 #include <boost/thread/mutex.hpp>
24 #include <boost/thread/thread.hpp>
25
26 #define BOOST_AUTO_TEST_MAIN
27 #include <boost/test/auto_unit_test.hpp>
28
29 #include <list>
30 #include <iostream>
31
32 class counter
33 {
34    public:
35       counter() : count(0) { }
36       
37     int increment() {
38         boost::mutex::scoped_lock scoped_lock(mutex);
39         return ++count;
40     }
41     
42 private:
43     boost::mutex mutex;
44     int count;
45 };
46
47
48 counter c;
49
50 class worker {
51 public:
52     void operator() (void) {
53         c.increment();
54     }
55 };
56
57 #define USE_GROUP 1
58
59
60 BOOST_AUTO_UNIT_TEST( thread_group )
61 {
62     try 
63     {
64         const int num_threads = 4;
65         boost::thread_group thrds;
66         
67         for (int i=0; i < num_threads; ++i)
68         {
69             worker w;
70             thrds.add_thread(new boost::thread(w));
71         }
72         thrds.join_all();
73     }
74     catch (...) 
75     {
76         BOOST_CHECK(false);
77     }
78     BOOST_CHECK(c.increment() == 5);
79 }
80
81
82 BOOST_AUTO_UNIT_TEST( thread_list )
83 {
84     try 
85     {
86         const int num_threads = 4;
87         std::list<boost::thread *> thread_list;
88         
89         for (int i=0; i < num_threads; ++i)
90         {
91             worker w;
92             thread_list.push_back(new boost::thread(w));
93         }
94         std::list<boost::thread *>::iterator it;
95         for (it = thread_list.begin(); it != thread_list.end(); it++)
96         {
97             (*it)->join();
98             delete *it;
99         }
100
101     }
102     catch (...) 
103     {
104         BOOST_CHECK(false);
105     }
106     BOOST_CHECK(c.increment() == 10);
107 }
108
109
110
111 /*
112  * Local variables:
113  * c-basic-offset: 4
114  * indent-tabs-mode: nil
115  * c-file-style: "stroustrup"
116  * End:
117  * vim: shiftwidth=4 tabstop=8 expandtab
118  */