File: condition_test_common.hpp

package info (click to toggle)
boost1.35 1.35.0-5
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 203,856 kB
  • ctags: 337,867
  • sloc: cpp: 938,683; xml: 56,847; ansic: 41,589; python: 18,999; sh: 11,566; makefile: 664; perl: 494; yacc: 456; asm: 353; csh: 6
file content (97 lines) | stat: -rw-r--r-- 2,264 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#ifndef CONDITION_TEST_COMMON_HPP
#define CONDITION_TEST_COMMON_HPP
// Copyright (C) 2007 Anthony Williams
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying 
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/thread/condition_variable.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread_time.hpp>

unsigned const timeout_seconds=5;
    
struct wait_for_flag
{
    boost::mutex mutex;
    boost::condition_variable cond_var;
    bool flag;
    unsigned woken;
        
    wait_for_flag():
        flag(false),woken(0)
    {}

    struct check_flag
    {
        bool const& flag;
            
        check_flag(bool const& flag_):
            flag(flag_)
        {}
            
        bool operator()() const
        {
            return flag;
        }
    private:
        void operator=(check_flag&);
    };

        
    void wait_without_predicate()
    {
        boost::mutex::scoped_lock lock(mutex);
        while(!flag)
        {
            cond_var.wait(lock);
        }
        ++woken;
    }

    void wait_with_predicate()
    {
        boost::mutex::scoped_lock lock(mutex);
        cond_var.wait(lock,check_flag(flag));
        if(flag)
        {
            ++woken;
        }
    }

    void timed_wait_without_predicate()
    {
        boost::system_time const timeout=boost::get_system_time()+boost::posix_time::seconds(timeout_seconds);
            
        boost::mutex::scoped_lock lock(mutex);
        while(!flag)
        {
            if(!cond_var.timed_wait(lock,timeout))
            {
                return;
            }
        }
        ++woken;
    }

    void timed_wait_with_predicate()
    {
        boost::system_time const timeout=boost::get_system_time()+boost::posix_time::seconds(timeout_seconds);
        boost::mutex::scoped_lock lock(mutex);
        if(cond_var.timed_wait(lock,timeout,check_flag(flag)) && flag)
        {
            ++woken;
        }
    }
    void relative_timed_wait_with_predicate()
    {
        boost::mutex::scoped_lock lock(mutex);
        if(cond_var.timed_wait(lock,boost::posix_time::seconds(timeout_seconds),check_flag(flag)) && flag)
        {
            ++woken;
        }
    }
};


#endif