1
// threadedtests.cpp - Tests for threaded code
5
* Copyright (C) 2008 10gen Inc.
7
* This program is free software: you can redistribute it and/or modify
8
* it under the terms of the GNU Affero General Public License, version 3,
9
* as published by the Free Software Foundation.
11
* This program is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
* GNU Affero General Public License for more details.
16
* You should have received a copy of the GNU Affero General Public License
17
* along with this program. If not, see <http://www.gnu.org/licenses/>.
21
#include "../util/mvar.h"
22
#include "../util/thread_pool.h"
23
#include <boost/thread.hpp>
24
#include <boost/bind.hpp>
28
namespace ThreadedTests {
30
template <int nthreads_param=10>
33
virtual void setup() {} //optional
34
virtual void subthread() = 0;
35
virtual void validate() = 0;
37
static const int nthreads = nthreads_param;
42
launch_subthreads(nthreads);
47
virtual ~ThreadedTest() {}; // not necessary, but makes compilers happy
50
void launch_subthreads(int remaining){
51
if (!remaining) return;
53
boost::thread athread(boost::bind(&ThreadedTest::subthread, this));
55
launch_subthreads(remaining - 1);
61
// Tested with up to 30k threads
62
class IsWrappingIntAtomic : public ThreadedTest<> {
63
static const int iterations = 1000000;
67
for(int i=0; i < iterations; i++){
68
//target.x++; // verified to fail with this version
69
target.atomicIncrement();
73
ASSERT_EQUALS(target.x , unsigned(nthreads * iterations));
77
class MVarTest : public ThreadedTest<> {
78
static const int iterations = 10000;
82
MVarTest() : target(0) {}
84
for(int i=0; i < iterations; i++){
85
int val = target.take();
86
#if BOOST_VERSION >= 103500
87
//increase chances of catching failure
88
boost::this_thread::yield();
94
ASSERT_EQUALS(target.take() , nthreads * iterations);
99
static const int iterations = 10000;
100
static const int nThreads = 8;
103
void increment(int n){
104
for (int i=0; i<n; i++){
105
counter.atomicIncrement();
111
ThreadPool tp(nThreads);
113
for (int i=0; i < iterations; i++){
114
tp.schedule(&WrappingInt::atomicIncrement, &counter);
115
tp.schedule(&ThreadPoolTest::increment, this, 2);
120
ASSERT(counter == (unsigned)(iterations * 3));
124
class All : public Suite {
126
All() : Suite( "threading" ){
130
add< IsWrappingIntAtomic >();
132
add< ThreadPoolTest >();