c++-gtk-utils
Main Page
Related Pages
Modules
Namespaces
Classes
Files
File List
File Members
c++-gtk-utils
notifier.h
Go to the documentation of this file.
1
/* Copyright (C) 2005 to 2011 Chris Vine
2
3
The library comprised in this file or of which this file is part is
4
distributed by Chris Vine under the GNU Lesser General Public
5
License as follows:
6
7
This library is free software; you can redistribute it and/or
8
modify it under the terms of the GNU Lesser General Public License
9
as published by the Free Software Foundation; either version 2.1 of
10
the License, or (at your option) any later version.
11
12
This library is distributed in the hope that it will be useful, but
13
WITHOUT ANY WARRANTY; without even the implied warranty of
14
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
Lesser General Public License, version 2.1, for more details.
16
17
You should have received a copy of the GNU Lesser General Public
18
License, version 2.1, along with this library (see the file LGPL.TXT
19
which came with this source code package in the c++-gtk-utils
20
sub-directory); if not, write to the Free Software Foundation, Inc.,
21
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22
23
*/
24
25
#ifndef CGU_NOTIFIER_H
26
#define CGU_NOTIFIER_H
27
28
/**
29
* @file notifier.h
30
* @brief This file provides a Notifier class to provide thread-safe
31
* signalling between a worker thread and the main program thread.
32
*
33
* For further details read this: Notifier.
34
*/
35
36
#include <unordered_set>
37
38
#include <pthread.h>
39
40
#include <
c++-gtk-utils/pipes.h
>
41
#include <
c++-gtk-utils/io_watch.h
>
42
#include <
c++-gtk-utils/emitter.h
>
43
#include <
c++-gtk-utils/cgu_config.h
>
44
45
namespace
Cgu {
46
47
/**
48
* @class Notifier notifier.h c++-gtk-utils/notifier.h
49
* @brief Provides thread-safe signalling between a worker thread and
50
* the main program thread.
51
* @sa Callback namespace Callback::post()
52
* @sa EmitterArg SafeEmitterArg Releaser
53
*
54
* The Notifier class provides thread-safe signalling between two
55
* threads. It does this through a pipe, to which an GSource (iowatch)
56
* object is attached to connect it to the glib program event loop. A
57
* functor is connected to the notifier, which is called in the
58
* receiving thread via the program event loop when operator()() (or
59
* emit()) is called on the Notifier object by the signalling thread.
60
* It therefore behaves like a SafeEmitter object, except that
61
* connected functors execute in the glib program event loop thread
62
* rather than in the thread which calls operator()()/emit().
63
*
64
* It is an alternative to the Callback::post() function in
65
* callback.h, and the documentation on callback.h contains a
66
* description of relevant trade-offs between the two.
67
*
68
* If the signalling thread is the same thread as that in which the
69
* functor connected to it will execute (which is the thread in which
70
* the default glib program event loop executes), executing it via the
71
* pipe would risk a deadlock - if the pipe fills up, the thread would
72
* block on write and never be able to read from the pipe to empty it.
73
* Accordingly, if the object is invoked by the same thread as that in
74
* which the functor will execute, this is detected and the functor
75
* will be invoked directly, rather than via the pipe. Therefore,
76
* actions so invoked may be out of order with those invoked by the
77
* other threads.
78
*
79
* If a Releaser object is passed as the second argument of
80
* Notifier::connect(), then a connected functor will automatically be
81
* disconnected if the object which has the Releaser object as a
82
* member is destroyed.
83
*
84
* The main use of Notifier objects is for a worker thread to signal
85
* an event to the main thread in which GTK+ is executing, which
86
* implies that GTK+ should also be executing in the default glib
87
* program event loop (GMainContext) (as will almost always be the
88
* case), which is the one with which the program first starts.
89
* Before a Notifier object is first used, it is a requirement that
90
* Notifier::init() (a static member function) be called in the thread
91
* in which the default glib event loop executes, and any connected
92
* functors will execute in that thread. Notifier::init() only needs
93
* to be called once at program start-up - it doesn't need to be
94
* called separately for each Notifier object, and can be called
95
* before any Notifier objects have been constructed. If it has not
96
* been called before the construction of the first Notifier object
97
* has taken place, it will occur automatically on that first
98
* construction. That means that if the first Notifier object is not
99
* constructed in the main (event loop) thread of the program, then
100
* Notifier::init() must be called explicitly before that first object
101
* is constructed. In addition, if glib < 2.32 is installed, before
102
* Notifier::init() is called (or the first Notifier object created)
103
* g_thread_init(0) should have been called: as a result a Notifier
104
* object cannot be a global (non-local) static object with glib <
105
* 2.32 (glib >= 2.32 does not require g_thread_init() to be called to
106
* be thread safe). It is a good idea also that Notifier::init()
107
* should have been called (or the first Notifier object constructed)
108
* before the main program thread creates any new threads. Then the
109
* state of initialisation effected by Notifier::init() will
110
* automatically be visible between threads.
111
*
112
* When executing a functor connected to a Notifier object, a check is
113
* made for a case where between the signalling thread invoking a
114
* Notifier object and the main program event loop calling that
115
* functor, the Notifier object ceases to exist. However there can
116
* still be a race condition if the lifetime of the Notifier object is
117
* determined outside the thread of execution of the main program
118
* event loop and a Notifier object is destroyed by that other thread
119
* between the time the check is made and the functor executed.
120
* Normally Notifier objects are constructed and destroyed in the main
121
* program thread, but where that is not the case the user will need
122
* to take this into account and if need be provide appropriate
123
* synchronisation to secure the lifetime of the Notifier object until
124
* after the functor has been called. Likewise, a Releaser object
125
* cannot offer protection if the remote object whose non-static
126
* method is represented by a connected functor is destroyed by
127
* another thread while the main program loop is in the middle of
128
* executing the functor. When the main loop begins invoking the
129
* execution of the callback, the remote object must either wholly
130
* exist (in which case the callback will be invoked) or have been
131
* destroyed (in which case the callback will be ignored), and not be
132
* in some transient half-state governed by another thread.
133
*
134
* Apart from that, the Notifier object is thread-safe and any of its
135
* methods may be invoked in any thread. (It is as thread-safe as a
136
* SafeEmitter object, as described in emitter.h, which contains
137
* further details on thread safety.)
138
*
139
* To pass variable data to a functor executed by the Notifier object,
140
* the AsyncQueue class can be employed.
141
*/
142
143
/*
144
For a program with two GMainContext program event loops (not a usual
145
case), it would be possible for a Notifier-like object to be
146
initialised in the non-default GMainContext thread, and execute in
147
that thread, by passing that other GMainContext object as the last
148
argument when calling start_iowatch() in Notifier::Notifier().
149
However, to conserve file descriptors all Notifier objects share a
150
common pipe and iowatch event watch, which implies that all Notifier
151
objects would also need to execute in that other thread. To get
152
around this it would be possible either to templatize Notifier with
153
tag types for different GMainContexts (so that there would be a
154
different static pipe/iowatch object for each GMainContext), or to
155
have thread-local storage for each of the static objects in the
156
Notifier class, but an easier solution for one-off cases would be to
157
have a version of Notifier which does not use static (shared)
158
PipeFifo and iowatch objects, at the expense of greater use of file
159
descriptor resources.
160
161
Such a special Notifier object could also be used to signal from a
162
Unix (asynchronous) signal/interrupt handler, but in that case the
163
write file descriptor of the pipe should be set non-blocking to
164
prevent the very unlikely but theoretically possible case (in a
165
program executing in a system under extreme load) of the pipe
166
filling up before being emptied by the Notifier::read_pipe_cb()
167
callback function executing in the main program and so blocking in
168
the handler, thus deadlocking the program.
169
*/
170
171
172
namespace
Thread {
173
class
Mutex;
174
}
175
176
class
Notifier;
177
178
class
Notifier
{
179
180
static
bool
initialised;
181
static
pthread_t thread_id;
182
// pointers can be keys of associative containers: "For templates
183
// greater, less, greater_equal, and less_equal, the specializations
184
// for any pointer type yield a total order, even if the built-in
185
// operators <, >, <=, >= do not." (para 20.3.3/8).
186
static
std::unordered_set<Notifier*> object_set;
187
static
PipeFifo
pipe;
188
static
Thread::Mutex
* set_mutex_p;
189
static
Thread::Mutex
* write_mutex_p;
190
static
void
read_pipe_cb(
bool
&);
191
192
SafeEmitter
emitter;
193
public
:
194
/**
195
* This class cannot be copied. The copy constructor is deleted.
196
*/
197
Notifier
(
const
Notifier
&) =
delete
;
198
199
/**
200
* This class cannot be copied. The assignment operator is deleted.
201
*/
202
Notifier
&
operator=
(
const
Notifier
&) =
delete
;
203
204
/**
205
* A utility which tells the caller whether it is in the thread in
206
* which the callback will execute (the main program thread). It will
207
* not throw. It is thread safe.
208
* @return true if the caller is in the thread in which the callback
209
* will execute, otherwise false.
210
*/
211
// don't make this a static member function - it can then only be called
212
// by object notation after a Notifier object has first been constructed,
213
// which means Notifier::init() must have been called
214
bool
in_main_thread
() {
return
pthread_equal(thread_id, pthread_self());}
215
216
/**
217
* This will cause the connected functors to be executed in the main
218
* program thread. It is thread safe (but see the comments in the
219
* introductory remarks above about race conditions where the lifetime
220
* of a Notifier object is determined by a thread other than the main
221
* program thread, and about protection by a Releaser object where a
222
* connected remote object is destroyed in mid-emission by another
223
* thread).
224
* @exception std::bad_alloc The method might throw std::bad_alloc if
225
* memory is exhausted and the system throws in that case, and this
226
* method is called in the thread in which the functors will execute
227
* (the main program thread). In addition, it will throw if the
228
* function or class methods represented by the functors throw (or if
229
* the assignment operator of a bound argument throws) and the call is
230
* made in that thread. If called in a different thread it will not
231
* throw (an exception thrown by a connected functor will be caught
232
* and reported in the iowatch dispatcher).
233
*/
234
void
emit
();
235
236
/**
237
* This will cause the connected functors to be executed in the main
238
* program thread. It is thread safe (but see the comments in the
239
* introductory remarks above about race conditions where the lifetime
240
* of a Notifier object is determined by a thread other than the main
241
* program thread, and about protection by a Releaser object where a
242
* connected remote object is destroyed in mid-emission by another
243
* thread).
244
* @exception std::bad_alloc The method might throw std::bad_alloc if
245
* memory is exhausted and the system throws in that case, and this
246
* method is called in the thread in which the functors will execute
247
* (the main program thread). In addition, it will throw if the
248
* function or class methods represented by the functors throw (or if
249
* the assignment operator of a bound argument throws) and the call is
250
* made in that thread. If called in a different thread it will not
251
* throw (an exception thrown by a connected functor will be caught
252
* and reported in the iowatch dispatcher).
253
*/
254
void
operator()
() {
emit
();}
255
256
/**
257
* Connects a functor. It is thread safe.
258
* @param f The functor to connect.
259
* @return The functor connected.
260
* @exception std::bad_alloc The method might throw std::bad_alloc if
261
* memory is exhausted and the system throws in that case.
262
*/
263
Callback::SafeFunctor
connect
(
const
Callback::SafeFunctor
& f);
264
265
/**
266
* Connects a functor. It is thread safe.
267
* @param f The functor to connect.
268
* @param r A Releaser object for automatic disconnection of the
269
* functor if the object whose method it represents is destroyed.
270
* @return The functor connected.
271
* @exception std::bad_alloc The method might throw std::bad_alloc if
272
* memory is exhausted and the system throws in that case.
273
*/
274
Callback::SafeFunctor
connect
(
const
Callback::SafeFunctor
& f,
Releaser
& r);
275
276
/**
277
* Disconnects a functor previously connected. This does not throw
278
* provided that the destructors of any bound arguments do not throw.
279
* It is thread safe.
280
* @param f The functor to disconnect.
281
*/
282
void
disconnect
(
const
Callback::SafeFunctor
& f);
283
284
/**
285
* Blocks a connected functor from executing in the main program
286
* thread when emit() or operator()() is called until unblock() is
287
* called. This method does not throw. It is thread safe.
288
* @param f The functor to block.
289
* @note This has effect immediately: it will block a pending emission
290
* for which emit() or operator()() has previously been called but
291
* which has not yet been tested for execution in the main loop.
292
*/
293
void
block
(
const
Callback::SafeFunctor
& f);
294
295
/**
296
* Unblocks a previously blocked functor. This method does not throw.
297
* It is thread safe.
298
* @param f The functor to unblock.
299
* @note This has effect immediately: it will unblock a pending
300
* emission for which emit() or operator()() has previously been
301
* called but which has not yet been tested for execution in the main
302
* loop.
303
*/
304
void
unblock
(
const
Callback::SafeFunctor
& f);
305
306
/**
307
* Initialises the program for the use of Notifier objects. It only
308
* needs to be called once at program start-up (it doesn't need to be
309
* called separately for each Notifier object), and can be called
310
* before any Notifier objects have been constructed. It should be
311
* called in the thread in which the default main glib event loop
312
* executes (the main program thread) before that thread creates any
313
* new threads.
314
* @exception std::bad_alloc This method might throw std::bad_alloc if
315
* memory is exhausted and the system throws in that case.
316
* @exception PipeError PipeError will be thrown if the static pipe
317
* used by Notifier objects cannot be initialised.
318
*/
319
static
void
init
();
320
321
/**
322
* The constructor is thread safe provided init() has previously been
323
* called before the main program thread creates any new threads.
324
* @exception std::bad_alloc The constructor might throw
325
* std::bad_alloc if memory is exhausted and the system throws in that
326
* case.
327
* @exception PipeError PipeError can be thrown if this is the first
328
* Notifier object to be constructed and Notifier::init() has not
329
* previously been called.
330
*/
331
Notifier
();
332
333
/**
334
* The destructor does not throw provided the destructors of any bound
335
* arguments do not throw and std::hash<T*>::operator()() does not
336
* throw (as it would not on any sane implementation). It is thread
337
* safe (but see the comments in the introductory remarks above about
338
* race conditions where the lifetime of a Notifier object is
339
* determined by a thread other than the main program thread).
340
*/
341
~Notifier
();
342
343
/* Only has effect if --with-glib-memory-slices-compat or
344
* --with-glib-memory-slices-no-compat option picked */
345
CGU_GLIB_MEMORY_SLICES_FUNCS
346
};
347
348
}
// namespace Cgu
349
350
#endif
Generated on Sun Jul 1 2012 09:21:43 for c++-gtk-utils by
1.8.1.1