Fawkes API Fawkes Development Version
qa_waitcond.cpp
1
2/***************************************************************************
3 * example_waitcond.cpp - wait condition example program
4 *
5 * Created: Sat Mar 01 15:13:44 2008
6 * Copyright 2006-2008 Tim Niemueller [www.niemueller.de]
7 *
8 ****************************************************************************/
9
10/* This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Library General Public License for more details.
19 *
20 * Read the full text in the LICENSE.GPL file in the doc directory.
21 */
22
23// Do not mention in API doc
24/// @cond EXAMPLES
25
26#include <core/exception.h>
27#include <core/threading/mutex.h>
28#include <core/threading/thread.h>
29#include <core/threading/wait_condition.h>
30
31#include <iostream>
32#include <string>
33
34using namespace std;
35using namespace fawkes;
36
37typedef enum { WAITER, WAKER } threadmode_t;
38
39class ExampleWaitCondThread : public Thread
40{
41public:
42 ExampleWaitCondThread(threadmode_t mode,
43 string tname,
44 WaitCondition *waitcond,
45 unsigned int sleep_time)
46 : Thread(tname.c_str(), Thread::OPMODE_CONTINUOUS)
47 {
48 mode_ = mode;
49 waitcond_ = waitcond;
50 sleep_time_ = sleep_time;
51 }
52
53 virtual void
54 loop()
55 {
56 if (mode_ == WAITER) {
57 usleep(sleep_time_);
58 cout << name() << ": Waiting for waker" << endl;
59 try {
60 waitcond_->wait();
61 cout << name() << ": Woken up" << endl;
62 } catch (Exception &e) {
63 cout << name() << ": EXCEPTION" << endl;
64 e.print_trace();
65 }
66 } else { // WAKER
67 usleep(sleep_time_);
68 cout << name() << ": Waking waiter" << endl;
69 waitcond_->wake_all();
70 cout << name() << ": Woke waiter" << endl;
71 }
72 }
73
74private:
75 threadmode_t mode_;
76 WaitCondition *waitcond_;
77 unsigned int sleep_time_;
78};
79
80int
81main(int argc, char **argv)
82{
84
85 ExampleWaitCondThread *t1 = new ExampleWaitCondThread(WAITER, "waiter1", w, 0);
86 ExampleWaitCondThread *t2 = new ExampleWaitCondThread(WAITER, "waiter2", w, 0);
87 ExampleWaitCondThread *tw = new ExampleWaitCondThread(WAKER, "waker", w, 2458642);
88
89 t1->start();
90 t2->start();
91 tw->start();
92
93 t1->join();
94 t2->join();
95 tw->join();
96
97 delete t1;
98 delete t2;
99 delete tw;
100
101 delete w;
102}
103
104/// @endcond
Base class for exceptions in Fawkes.
Definition: exception.h:36
void print_trace() noexcept
Prints trace to stderr.
Definition: exception.cpp:601
Thread class encapsulation of pthreads.
Definition: thread.h:46
Wait until a given condition holds.
Fawkes library namespace.