c++-gtk-utils: thread.h Source File

c++-gtk-utils

- Main Page
- Related Pages
- Modules
- Namespaces
- Classes
- Files

- File List
- File Members

thread.h
Go to the documentation of this file.
1 /* Copyright (C) 2005 to 2014 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_THREAD_H
26 #define CGU_THREAD_H
27
28 #include <memory> // for std::unique_ptr
29 #include <utility> // for std::move
30
31 #include <pthread.h>
32
33 #include <c++-gtk-utils/callback.h>
34 #include <c++-gtk-utils/mutex.h>
35 #include <c++-gtk-utils/cgu_config.h>
36
37 namespace Cgu {
38
39 namespace Thread {
40
41 /**
42 * @class Cgu::Thread::Thread thread.h c++-gtk-utils/thread.h
43 * @brief A class representing a pthread thread.
44 * @sa Thread::Mutex Thread::Mutex::Lock Thread::Cond Thread::Future Thread::JoinableHandle
45 *
46 * The Thread class encapsulates a pthread thread. It can start, join
47 * and cancel a thread.
48 *
49 * The Thread class, and the other thread related classes provided by
50 * this library such as Mutex, RecMutex, RWLock, CancelBlock and Cond,
51 * can be used interchangeably with (and mixed with) GThread objects
52 * and functions, and with GMutex, GRecMutex, GRWLock, GCond and
53 * similar, as they all use pthreads underneath on POSIX and other
54 * unix-like OSes.
55 *
56 * In addition, the thread related classes provided by this library
57 * can be used in conjunction with threads started with C++11/14
58 * threading facilities, and vice versa, as in C++11/14 on unix-like
59 * OSes these facilities are likely to be built on top of pthreads
60 * (for which purpose C++11/14 provides the std::native_handle_type
61 * type and std::thread::native_handle() function). Even where they
62 * are not, they will use the same threading primitives provided by
63 * the kernel: §30.3 of the C++11 standard states, albeit
64 * non-normatively, that "These threads [std::thread threads] are
65 * intended to map one-to-one with operating system threads".
66 *
67 * If in doubt, always use this library's thread related classes as
68 * they are guaranteed to be compatible with glib/gtk+ and with the
69 * native platform libraries. However, such doubts are in practice
70 * unnecessary: it is in practice inconceivable that C++11/14's
71 * threading implementation will be incompatible with the platform's
72 * native threading implementation (pthreads), because any practical
73 * program using C++11/14 threads is going to call into platform
74 * libraries, and those libraries may themselves be threaded or make
75 * thread related calls. So use whichever appears to suit the
76 * particular case better.
77 *
78 * @anchor ThreadsAnchor
79 * @b c++-gtk-utils @b library @b and @b C++11/14 @b threads
80 *
81 * As mentioned above, the thread facilities provided by this library
82 * can be freely interchanged with the threading facilities provided
83 * by C++11/14.
84 *
85 * The main features available from this library and not C++11/14 are
86 * thread cancellation and the associated Cgu::Thread::CancelBlock
87 * class, the Cgu::Thread::JoinableHandle class for scoped joinable
88 * thread handling and the Cgu::Thread::TaskManager class for running
89 * and composing tasks on a thread pool.
90 *
91 * C++11/14 does not provide thread cancellation or interruption
92 * support, and C++ will never be able to do so on a complete basis
93 * because to do so requires support from the underlying OS, which
94 * therefore makes it platform specific (in this case, POSIX
95 * specific): cancellation is only of limited use if it cannot
96 * reliably interrupt blocking system calls. The POSIX specification
97 * sets out the interruptible cancellation points in System
98 * Interfaces, section 2.9.5, Cancellation Points, and in effect
99 * specifies all the system calls which can block as cancellation
100 * points.
101 *
102 * Whether, in C++ programs, destructors of local objects in the
103 * cancelled thread are called is also system specific and is not
104 * specified by POSIX. Most modern commercial unixes, and recent
105 * linux/BSD distributions based on NPTL (in the case of Linux, those
106 * based on 2.6/3.* kernels), will unwind the stack and call
107 * destructors on thread cancellation by means of a pseudo-exception,
108 * but older distributions relying on the former linuxthreads
109 * implementation will not. Therefore for maximum portability
110 * cancellation would only be used where there are plain data
111 * structures/built-in types in existence in local scope when it
112 * occurs, and if there is anything in free store to be released
113 * clean-ups would be implemented with
114 * pthread_cleanup_push()/pthread_cleanup_pop(). This should be
115 * controlled with pthread_setcancelstate() and/or the CancelBlock
116 * class to choose the cancellation point.
117 *
118 * One of the (perhaps odd) features of C++11/14 threads is that if
119 * the destructor of a std::thread object is called which represents a
120 * joinable thread which has not been detach()ed or join()ed, the
121 * whole program is terminated with a call to std::terminate(), which
122 * makes it difficult to use in the presence of exceptions. Often
123 * what is wanted however is for join() to be called on a joinable
124 * thread where the associated thread object goes out of scope, or
125 * (provided it is done carefully and knowingly) for detach() to be
126 * called. The Cgu::Thread::JoinableHandle class can be used where
127 * either of these two is the appropriate response to this situation.
128 *
129 * In addition, the c++-gtk-utils library provides the following which
130 * are not present in C++11 and/or C++14: a guaranteed monotonic clock
131 * on timed condition variable waits where the operating system
132 * supports them; read-write locks/shared mutexes (present in C++14
133 * but not C++11); a Cgu::Thread::Future object which is more
134 * intuitive to use than C++11/14 futures and features a built in
135 * Cgu::SafeEmitter object which emits when the particular task has
136 * completed, and (since version 2.0.2) has associated
137 * Cgu::Thread::Future::when() methods for passing the result to a
138 * glib main loop; and (since version 2.2.2)
139 * Cgu::Thread::parallel_for_each() and
140 * Cgu::Thread::parallel_transform() functions for use with
141 * Cgu::Thread::TaskManager objects.
142 *
143 * @b c++-gtk-utils @b library @b and @b gthreads
144 *
145 * As mentioned above, the thread facilities provided by this library
146 * can be freely interchanged with the threading facilities provided
147 * by glib.
148 *
149 * The main features available with this thread implementation and not
150 * GThreads are thread cancellation, the mutex scoped locking classes
151 * Cgu::Thread::Mutex::Lock and Cgu::Thread::RecMutex::Lock, the
152 * joinable thread scoped management class Cgu::Thread::JoinableHandle
153 * and the Cgu::Thread::Future class (abstracting thread functions
154 * which provide a result).
155 *
156 * There is no need from the perspective of this class to call
157 * g_thread_init() before Cgu::Thread::Thread::start() is called, but
158 * prior to glib version 2.32 glib itself is not thread-safe without
159 * g_thread_init(), so where this class is used with glib < 2.32,
160 * g_thread_init() should be called at program initialization.
161 *
162 * See @ref Threading for particulars about GTK+ thread safety.
163 */
164
165
166 class Thread {
167 pthread_t thread;
168 // private constructor - this class can only be created with Thread::start
169 Thread() {}
170 public:
171 /**
172 * This class cannot be copied: it is intended to be held by
173 * std::unique_ptr. The copy constructor is deleted.
174 */
175 Thread(const Thread&) = delete;
176
177 /**
178 * This class cannot be copied: it is intended to be held by
179 * std::unique_ptr. The assignment operator is deleted.
180 */
181 Thread& operator=(const Thread&) = delete;
182
183 /**
184 * Cancels the thread represented by this Thread object. It can be
185 * called by any thread. The effect is undefined if the thread
186 * represented by this Thread object has both (a) already terminated
187 * and (b) been detached or had a call to join() made for it.
188 * Accordingly, if the user is not able to establish from the program
189 * logic whether the thread has terminated, the thread must be created
190 * as joinable and cancel() must not be called after a call to
191 * detach() has been made or a call to join() has returned. A
192 * Thread::JoinableHandle object can used to ensure this. It does not
193 * throw.
194 * @note Use this method with care - sometimes its use is unavoidable
195 * but destructors for local objects may not be called if a thread
196 * exits by virtue of a call to cancel() (that depends on the
197 * implementation). Most modern commercial unixes, and recent
198 * linux/BSD distributions based on NPTL, will unwind the stack and
199 * call destructors on thread cancellation by means of a
200 * pseudo-exception, but older distributions relying on the former
201 * linuxthreads implementation will not. Therefore for maximum
202 * portability only have plain data structures/built-in types in
203 * existence in local scope when it occurs and if there is anything in
204 * free store to be released implement clean-ups with
205 * pthread_cleanup_push()/pthread_cleanup_pop(). This should be
206 * controlled with pthread_setcancelstate() and/or the CancelBlock
207 * class to choose the cancellation point.
208 * @sa Cgu::Thread::Exit
209 */
210 void cancel() noexcept {pthread_cancel(thread);}
211
212 /**
213 * Joins the thread represented by this Thread object (that is, waits
214 * for it to terminate). It can be called by any thread other than
215 * the one represented by this Thread object. The result is undefined
216 * if the thread is or was detached or join() has already been called
217 * for the thread (a Thread::JoinableHandle object will however give a
218 * defined result in such cases for threads originally started as
219 * joinable). It does not throw.
220 */
221 void join() noexcept {pthread_join(thread, 0);}
222
223 /**
224 * Detaches the thread represented by this Thread object where it is
225 * joinable, so as to make it unjoinable. The effect is unspecified
226 * if the thread is already unjoinable (a Thread::JoinableHandle
227 * object will however give a defined result in such cases for threads
228 * originally started as joinable). It does not throw.
229 */
230 void detach() noexcept {pthread_detach(thread);}
231
232 /**
233 * Specifies whether the calling thread is the same thread as is
234 * represented by this Thread object. The effect is undefined if the
235 * thread represented by this Thread object has both (a) already
236 * terminated and (b) been detached or had a call to join() made for
237 * it. Accordingly, if the user is not able to establish from the
238 * program logic whether the thread has terminated, the thread must be
239 * created as joinable and is_caller() must not be called after a call
240 * to detach() has been made or a call to join() has returned. A
241 * Thread::JoinableHandle object can used to ensure this. This method
242 * does not throw.
243 * @return Returns true if the caller is in the thread represented by
244 * this Thread object.
245 */
246 bool is_caller() noexcept {return pthread_equal(thread, pthread_self());}
247
248 /**
249 * Starts a new thread. It can be called by any thread.
250 * @param cb A callback object (created by Callback::make(),
251 * Callback::make_ref() or Callback::lambda()) encapsulating the
252 * function to be executed by the new thread. The Thread object
253 * returned by this function will take ownership of the callback: it
254 * will automatically be deleted either by the new thread when it has
255 * finished with it, or by this method in the calling thread if the
256 * attempt to start a new thread fails (including if std::bad_alloc is
257 * thrown).
258 * @param joinable Whether the join() method may be called in relation
259 * to the new thread.
260 * @return A Thread object representing the new thread which has been
261 * started, held by a std::unique_ptr object as it has single
262 * ownership semantics. The std::unique_ptr object will be empty
263 * (that is std::unique_ptr<Cgu::Thread::Thread>::get() will return 0)
264 * if the thread did not start correctly, which would mean that memory
265 * is exhausted, the pthread thread limit has been reached or pthread
266 * has run out of other resources to start new threads.
267 * @exception std::bad_alloc This method might throw std::bad_alloc if
268 * memory is exhausted and the system throws in that case. (This
269 * exception will not be thrown if the library has been installed
270 * using the \--with-glib-memory-slices-no-compat configuration
271 * option: instead glib will terminate the program if it is unable to
272 * obtain memory from the operating system.) If this exception is
273 * thrown, the thread will not have started.
274 * @note 1. The thread will keep running even if the return value of
275 * start() goes out of scope (but it will no longer be possible to
276 * call any of the methods in this class for it, which is fine if the
277 * thread is not started as joinable and it is not intended to cancel
278 * it).
279 * @note 2. If the thread is started with the joinable attribute, the
280 * user must subsequently either call the join() or the detach()
281 * method, as otherwise a resource leak may occur (the destructor of
282 * this class does not call detach() automatically). Alternatively,
283 * the return value of this method can be passed to a
284 * Thread::JoinableHandle object which will do this automatically in
285 * the Thread::JoinableHandle object's destructor.
286 * @note 3. Any Thread::Exit exception thrown from the function
287 * executed by the new thread will be caught and consumed. The thread
288 * will safely terminate and unwind the stack in so doing.
289 * @note 4. If any uncaught exception other than Thread::Exit is
290 * allowed to propagate from the initial function executed by the new
291 * thread, the exception is not consumed (NPTL's forced stack
292 * unwinding on cancellation does not permit catching with an ellipsis
293 * argument without rethrowing, and even if it did permit it, the
294 * result would be an unreported error). The C++11 standard requires
295 * std::terminate() to be called in such a case and so the entire
296 * program terminated. Accordingly, a user must make sure that no
297 * exceptions, other than Thread::Exit or any cancellation
298 * pseudo-exception, can propagate from the initial function executed
299 * by the new thread. This includes ensuring that, for any argument
300 * passed to that function which is not a built-in type and which is
301 * not taken by the function by const or non-const reference, the
302 * argument type's copy constructor does not throw.
303 */
304 static std::unique_ptr<Cgu::Thread::Thread> start(const Cgu::Callback::Callback* cb,
305 bool joinable);
306
307 /**
308 * Starts a new thread. It can be called by any thread.
309 * @param func A callable object, such as formed by a lambda
310 * expression or the result of std::bind, which will be executed by
311 * the new thread.
312 * @param joinable Whether the join() method may be called in relation
313 * to the new thread.
314 * @return A Thread object representing the new thread which has been
315 * started, held by a std::unique_ptr object as it has single
316 * ownership semantics. The std::unique_ptr object will be empty
317 * (that is std::unique_ptr<Cgu::Thread::Thread>::get() will return 0)
318 * if the thread did not start correctly, which would mean that memory
319 * is exhausted, the pthread thread limit has been reached or pthread
320 * has run out of other resources to start new threads.
321 * @exception std::bad_alloc This method might throw std::bad_alloc if
322 * memory is exhausted and the system throws in that case. (This
323 * exception will not be thrown if the library has been installed
324 * using the \--with-glib-memory-slices-no-compat configuration
325 * option: instead glib will terminate the program if it is unable to
326 * obtain memory from the operating system.) If this exception is
327 * thrown, the thread will not have started.
328 * @note 1. This function may also throw if the copy or move
329 * constructor of the callable object throws. If that happens, the
330 * thread will not have started.
331 * @note 2. The thread will keep running even if the return value of
332 * start() goes out of scope (but it will no longer be possible to
333 * call any of the methods in this class for it, which is fine if the
334 * thread is not started as joinable and it is not intended to cancel
335 * it).
336 * @note 3. If the thread is started with the joinable attribute, the
337 * user must subsequently either call the join() or the detach()
338 * method, as otherwise a resource leak may occur (the destructor of
339 * this class does not call detach() automatically). Alternatively,
340 * the return value of this method can be passed to a
341 * Thread::JoinableHandle object which will do this automatically in
342 * the Thread::JoinableHandle object's destructor.
343 * @note 4. Any Thread::Exit exception thrown from the function
344 * executed by the new thread will be caught and consumed. The thread
345 * will safely terminate and unwind the stack in so doing.
346 * @note 5. If any uncaught exception other than Thread::Exit is
347 * allowed to propagate from the initial function executed by the new
348 * thread, the exception is not consumed (NPTL's forced stack
349 * unwinding on cancellation does not permit catching with an ellipsis
350 * argument without rethrowing, and even if it did permit it, the
351 * result would be an unreported error). The C++11 standard requires
352 * std::terminate() to be called in such a case and so the entire
353 * program terminated. Accordingly, a user must make sure that no
354 * exceptions, other than Thread::Exit or any cancellation
355 * pseudo-exception, can propagate from the initial function executed
356 * by the new thread. This includes ensuring that, for any bound
357 * argument passed to that function which is not a built-in type and
358 * which is not taken by the function by const or non-const reference,
359 * the argument type's copy constructor does not throw.
360 *
361 * Since 2.1.0
362 */
363 // we need to use enable_if so that where this function is passed a
364 // pointer to non-const Callback::Callback, or some other convertible
365 // pointer, this templated overload is dropped from the overload set,
366 // in order to support the Callback::Callback pointer overloads of
367 // this function. This overload calls into the version of this
368 // function taking a pointer to const Callback::Callback in order to
369 // perform type erasure.
370 template <class F,
371 class = typename std::enable_if<!std::is_convertible<typename std::remove_reference<F>::type,
372 const Cgu::Callback::Callback*>::value>::type>
373 static std::unique_ptr<Cgu::Thread::Thread> start(F&& func,
374 bool joinable) {
375 return start(Cgu::Callback::lambda<>(std::forward<F>(func)), joinable);
376 }
377
378 #ifdef CGU_USE_GLIB_MEMORY_SLICES_NO_COMPAT
379 CGU_GLIB_MEMORY_SLICES_FUNCS
380 #endif
381 };
382
383 /**
384 * @class Cgu::Thread::JoinableHandle thread.h c++-gtk-utils/thread.h
385 * @brief A class wrapping a Thread::Thread object representing a
386 * joinable thread.
387 * @sa Thread::Thread Thread::Future
388 *
389 * This class enables a joinable thread to be made more easily
390 * exception safe. It can also be used to provide that a joinable
391 * thread is not detached or joined while other methods dependent on
392 * that might still be called, and to provide a defined result where
393 * there are multiple calls to join() and/or detach(). When it is
394 * destroyed, it will either detach or join the thread represented by
395 * the wrapped Thread::Thread object unless it has previously been
396 * detached or joined using the detach() or join() methods, so
397 * avoiding thread resource leaks. Whether it will detach() or join()
398 * on destruction depends on the Thread::JoinableHandle::Action
399 * argument passed to the
400 * Thread::JoinableHandle::JoinableHandle(std::unique_ptr<Thread::Thread>,
401 * Action) constructor.
402 *
403 * Passing Thread::JoinableHandle::detach_on_exit to that argument is
404 * not always the correct choice where the thread callback has been
405 * bound to a reference argument in local scope and an exception might
406 * be thrown, because the thread will keep running after the
407 * Thread::JoinableHandle object and other local variables have
408 * (because of the exception) gone out of scope. Consider the
409 * following trivial parallelized calculation example:
410 *
411 * @code
412 * std::vector<int> get_readings();
413 * void get_mean(const std::vector<int>& v, int& result);
414 * void get_std_deviation(const std::vector<int>& v, int& result); // might throw
415 * void show_result(int mean, int deviation);
416 *
417 * using namespace Cgu;
418 * void do_calc() {
419 * int i, j;
420 * std::vector<int> v = get_readings();
421 * std::unique_ptr<Thread::Thread> t =
422 * Thread::Thread::start(std::bind(&get_mean, std::cref(v), std::ref(i)), true);
423 * if (t.get()) { // checks whether thread started correctly
424 * get_std_deviation(v, j);
425 * t->join();
426 * show_result(i, j);
427 * }
428 * }
429 * @endcode
430 *
431 * If get_std_deviation() throws, as well as there being a potential
432 * thread resource leak by virtue of no join being made, the thread
433 * executing get_mean() will continue running and attempt to access
434 * variable v, and put its result in variable i, which may by then
435 * both be out of scope. To deal with such a case, the thread could
436 * be wrapped in a Thread::JoinableHandle object which joins on exit
437 * rather than detaches, for example:
438 *
439 * @code
440 * ...
441 * using namespace Cgu;
442 * void do_calc() {
443 * int i, j;
444 * std::vector<int> v = get_readings();
445 * Thread::JoinableHandle t{Thread::Thread::start(std::bind(&get_mean, std::cref(v), std::ref(i)), true),
446 * Thread::JoinableHandle::join_on_exit};
447 * if (t.is_managing()) { // checks whether thread started correctly
448 * get_std_deviation(v, j);
449 * t.join();
450 * show_result(i, j);
451 * }
452 * }
453 * @endcode
454 *
455 * Better still, however, would be to use Cgu::Thread::Future in this
456 * kind of usage, namely a usage where a worker thread is intended to
457 * provide a result for inspection.
458 *
459 * @note These examples assume that the std::vector library
460 * implementation permits concurrent reads of a vector object by
461 * different threads. Whether that is the case depends on the
462 * documentation of the library concerned (if designed for a
463 * multi-threaded environment, most will permit this).
464 */
465 class JoinableHandle {
466 public:
467 enum Action {detach_on_exit, join_on_exit};
468
469 private:
470 Mutex mutex; // make this the first member so the constructors are strongly exception safe
471 Action action;
472 bool detached;
473 std::unique_ptr<Cgu::Thread::Thread> thread;
474
475 public:
476 /**
477 * Cancels the thread represented by the wrapped Thread::Thread
478 * object. It can be called by any thread. The effect is undefined
479 * if when called the thread represented by the wrapped Thread::Thread
480 * object has both (a) already terminated and (b) had a call to join()
481 * or detach() made for it. Accordingly, if the user is not able to
482 * establish from the program logic whether the thread has terminated,
483 * cancel() must not be called after a call to detach() has been made
484 * or a call to join() has returned: this can be ensured by only
485 * detaching or joining via this object's destructor (that is, by not
486 * using the explicit detach() and join() methods). This method does
487 * not throw.
488 * @note Use this method with care - see Thread::cancel() for further
489 * information.
490 */
491 void cancel();
492
493 /**
494 * Joins the thread represented by the wrapped Thread::Thread object
495 * (that is, waits for it to terminate), unless the detach() or join()
496 * method has previously been called in which case this call does
497 * nothing. It can be called by any thread other than the one
498 * represented by the wrapped Thread::Thread object, but only one
499 * thread can wait on it: if one thread (thread A) calls it while
500 * another thread (thread B) is already blocking on it, thread A's
501 * call to this method will return immediately and return false. It
502 * does not throw.
503 * @return true if a successful join() has been accomplished (that is,
504 * detach() or join() have not previously been called), otherwise
505 * false.
506 */
507 bool join();
508
509 /**
510 * Detaches the thread represented by this Thread::Thread object, so
511 * as to make it unjoinable, unless the detach() or join() method has
512 * previously been called in which case this call does nothing. It
513 * does not throw.
514 */
515 void detach();
516
517 /**
518 * Specifies whether the calling thread is the same thread as is
519 * represented by the wrapped Thread::Thread object. It can be called
520 * by any thread. The effect is undefined if the thread represented
521 * by the wrapped Thread::Thread object has both (a) already
522 * terminated and (b) had a call to join() or detach() made for it.
523 * Accordingly, if the user is not able to establish from the program
524 * logic whether the thread has terminated, is_caller() must not be
525 * called after a call to detach() has been made or a call to join()
526 * has returned: this can be ensured by only detaching or joining via
527 * this object's destructor (that is, by not using the explicit
528 * detach() and join() methods). This method does not throw.
529 * @return Returns true if the caller is in the thread represented by
530 * the wrapped Thread::Thread object. If not, or this JoinableHandle
531 * does not wrap any Thread object, then returns false.
532 */
533 bool is_caller();
534
535 /**
536 * Specifies whether this JoinableHandle object has been initialized
537 * with a Thread::Thread object representing a correctly started
538 * thread in respect of which neither JoinableHandle::detach() nor
539 * JoinableHandle::join() has been called. It can be called by any
540 * thread. It is principally intended to enable the constructor
541 * taking a std::unique_ptr<Cgu::Thread::Thread> object to be directly
542 * initialized by a call to Thread::Thread::start(), by providing a
543 * means for the thread calling Thread::Thread::start() to check
544 * afterwards that the new thread did, in fact, start correctly. Note
545 * that this method will return true even after the thread has
546 * finished, provided neither the join() nor detach() method has been
547 * called.
548 * @return Returns true if this object has been initialized by a
549 * Thread::Thread object representing a correctly started thread in
550 * respect of which neither JoinableHandle::detach() nor
551 * JoinableHandle::join() has been called, otherwise false.
552 */
553 bool is_managing();
554
555 /**
556 * Moves one JoinableHandle object to another JoinableHandle object.
557 * This is a move operation which transfers ownership to the assignee,
558 * as the handles store their Thread::Thread object by
559 * std::unique_ptr<>. Any existing thread managed by the assignee
560 * prior to the move will be detached if it has not already been
561 * detached or joined. This method will not throw.
562 * @param h The assignor/movant, which will cease to hold a valid
563 * Thread::Thread object after the move has taken place.
564 * @return A reference to the assignee JoinableHandle object after
565 * assignment.
566 * @note This method is thread safe as regards the assignee (the
567 * object assigned to), but no synchronization is carried out with
568 * respect to the rvalue assignor/movant. This is because temporaries
569 * are only visible and accessible in the thread carrying out the move
570 * operation and synchronization for them would represent pointless
571 * overhead. In a case where the user uses std::move to force a move
572 * from a named object, and that named object's lifetime is managed by
573 * (or the object is otherwise accessed by) a different thread than
574 * the one making the move, the user must carry out her own
575 * synchronization with respect to that different thread, as the named
576 * object will be mutated by the move.
577 */
578 JoinableHandle& operator=(JoinableHandle&& h);
579
580 /**
581 * This constructor initializes a new JoinableHandle object with a
582 * std::unique_ptr<Thread::Thread> object, as provided by
583 * Thread::Thread::start(). This is a move operation which transfers
584 * ownership to the new object.
585 * @param thr The initializing Thread::Thread object (which must have
586 * been created as joinable) passed by a std::unique_ptr smart
587 * pointer. This is a move operation.
588 * @param act Either Thread::JoinableHandle::detach_on_exit (which
589 * will cause the destructor to detach the thread if it has not
590 * previously been detached or joined) or
591 * Thread::JoinableHandle::join_on_exit (which will cause the
592 * destructor to join the thread if it has not previously been
593 * detached or joined).
594 * @exception Cgu::Thread::MutexError Throws this exception if
595 * initialization of the internal mutex fails. The constructor is
596 * strongly exception safe: if Cgu::Thread::MutexError is thrown, the
597 * initializing std::unique_ptr<Cgu::Thread::Thread> object will be
598 * left unchanged. (It is often not worth checking for this
599 * exception, as it means either memory is exhausted or pthread has
600 * run out of other resources to create new mutexes.)
601 * @note 1. It is not necessary to check that the thread parameter
602 * represents a correctly started thread (that is, that thr.get() does
603 * not return 0) before this constructor is invoked, because that can
604 * be done after construction by calling JoinableHandle::is_managing()
605 * (a JoinableHangle object can safely handle a case where thr.get()
606 * does return 0). This enables a JoinableHandle object to be
607 * directly initialized by this constructor from a call to
608 * Thread::Thread::start().
609 * @note 2. No synchronization is carried out with respect to the
610 * initializing std::unique_ptr object. This is because such an
611 * object is usually passed to this constructor as a temporary, which
612 * is only visible and accessible in the thread carrying out the move
613 * operation, in which case synchronization would represent pointless
614 * overhead. In a case where the user uses std::move to force a move
615 * from a named std::unique_ptr object, and that named object's
616 * lifetime is managed by (or the object is otherwise accessed by) a
617 * different thread than the one making the move, the user must carry
618 * out her own synchronization with respect to that different thread,
619 * as the initializing std::unique_ptr object will be mutated by the
620 * move.
621 * @sa JoinableHandle::is_managing().
622 */
623 JoinableHandle(std::unique_ptr<Cgu::Thread::Thread> thr, Action act): action(act), detached(false), thread(std::move(thr)) {}
624
625 /**
626 * This constructor initializes a new JoinableHandle object with an
627 * existing JoinableHandle object. This is a move operation which
628 * transfers ownership to the new object.
629 * @param h The initializing JoinableHandle object, which will cease
630 * to hold a valid Thread::Thread object after the initialization has
631 * taken place.
632 * @exception Cgu::Thread::MutexError Throws this exception if
633 * initialization of the internal mutex fails. The constructor is
634 * strongly exception safe: if Cgu::Thread::MutexError is thrown, the
635 * initializing Cgu::Thread::JoinableHandle object will be left
636 * unchanged. (It is often not worth checking for this exception, as
637 * it means either memory is exhausted or pthread has run out of other
638 * resources to create new mutexes.)
639 * @note No synchronization is carried out with respect to the
640 * initializing rvalue. This is because temporaries are only visible
641 * and accessible in the thread carrying out the move operation and
642 * synchronization for them would represent pointless overhead. In a
643 * case where a user uses std::move to force a move from a named
644 * object, and that named object's lifetime is managed by (or the
645 * object is otherwise accessed by) a different thread than the one
646 * making the move, the user must carry out her own synchronization
647 * with respect to that different thread, as the named object will be
648 * mutated by the move.
649 */
650 JoinableHandle(JoinableHandle&& h): action(h.action), detached(h.detached), thread(std::move(h.thread)) {}
651
652 /**
653 * The default constructor. Nothing is managed until the move
654 * assignment operator has been called.
655 * @exception Cgu::Thread::MutexError Throws this exception if
656 * initialization of the internal mutex fails. (It is often not worth
657 * checking for this exception, as it means either memory is exhausted
658 * or pthread has run out of other resources to create new mutexes.)
659 *
660 * Since 2.0.8
661 */
662 JoinableHandle(): action(detach_on_exit), detached(true) {}
663
664 /**
665 * The destructor will detach a managed thread (if the
666 * Thread::JoinableHandle::detach_on_exit flag is set) or join it (if
667 * the Thread::JoinableHandle::join_on_exit flag is set), unless it
668 * has previously been detached or joined with the detach() or join()
669 * methods. The destructor is thread safe (any thread may destroy the
670 * JoinableHandle object). The destructor will not throw.
671 */
672 ~JoinableHandle();
673
674 /* Only has effect if --with-glib-memory-slices-compat or
675 * --with-glib-memory-slices-no-compat option picked */
676 CGU_GLIB_MEMORY_SLICES_FUNCS
677 };
678
679 /**
680 * @class CancelBlock thread.h c++-gtk-utils/thread.h
681 * @brief A class enabling the cancellation state of a thread to be
682 * controlled.
683 *
684 * A class enabling the cancellation state of a thread to be
685 * controlled, so as to provide exception safe cancellation state
686 * changes. When a CancelBlock object goes out of scope, the thread's
687 * cancellation state is returned to the state it was in immediately
688 * prior to the object's construction.
689 *
690 * Cancellation state can be changed before a CancelBlock object goes
691 * out of scope by calling its block() and unblock() methods.
692 * However, care should be taken if calling unblock() for the purpose
693 * of enabling thread cancellation while the CancelBlock object is
694 * still in existence: this should normally only be done if the
695 * thread's cancellation state at the time the CancelBlock object was
696 * constructed (which is the cancellation state to which the thread
697 * will be restored when the object goes out of scope) was
698 * PTHREAD_CANCEL_DISABLE. This is because when a thread begins
699 * cancellation the POSIX standard states that it will automatically
700 * switch itself into a PTHREAD_CANCEL_DISABLE state (see System
701 * Interfaces, section 2.9.5, Thread Cancellation Cleanup Handlers),
702 * and the POSIX standard further states that the behaviour is
703 * undefined if a cancellation handler attempts to enable cancellation
704 * again while the thread is cleaning up - and any thread
705 * implementation such as NPTL which unwinds the stack on cancellation
706 * will do so if the CancelBlock's destructor would restore to
707 * PTHREAD_CANCEL_ENABLE state. Whilst it is to be expected that any
708 * cancellation stack unwinding implementation will behave sensibly in
709 * these circumstances, this is not mandated by POSIX, so making code
710 * relying on this less portable.
711 *
712 * For these reasons, the same care should be exercised if passing
713 * 'false' to the CancelBlock constructor's 'blocking' argument.
714 */
715
716 class CancelBlock {
717 int starting_state;
718 public:
719 /**
720 * This class cannot be copied. The copy constructor is deleted.
721 */
722 CancelBlock(const CancelBlock&) = delete;
723
724 /**
725 * This class cannot be copied. The assignment operator is deleted.
726 */
727 CancelBlock& operator=(const CancelBlock&) = delete;
728
729 /**
730 * Makes the thread uncancellable, even if the code passes through a
731 * cancellation point, while the CancelBlock object exists (when the
732 * CancelBlock object ceases to exist, cancellation state is returned
733 * to the state prior to it being constructed). It should only be
734 * called by the thread which created the CancelBlock object. This
735 * method will not throw.
736 * @param old_state Indicates the cancellation state of the calling
737 * thread immediately before this call to block() was made, either
738 * PTHREAD_CANCEL_ENABLE (if the thread was previously cancellable) or
739 * PTHREAD_CANCEL_DISABLE (if this call did nothing because the thread
740 * was already uncancellable).
741 * @return 0 if successful, else a value other than 0.
742 */
743 static int block(int& old_state) noexcept {return pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);}
744
745 /**
746 * Makes the thread uncancellable, even if the code passes through a
747 * cancellation point, while the CancelBlock object exists (when the
748 * CancelBlock object ceases to exist, cancellation state is returned
749 * to the state prior to it being constructed). It should only be
750 * called by the thread which created the CancelBlock object. This
751 * method will not throw.
752 * @return 0 if successful, else a value other than 0.
753 */
754 static int block() noexcept {int old_state; return block(old_state);}
755
756 /**
757 * Makes the thread cancellable while the CancelBlock object exists
758 * (when the CancelBlock object ceases to exist, cancellation state is
759 * returned to the state prior to it being constructed). It should
760 * only be called by the thread which created the CancelBlock object.
761 * This method will not throw. The 'Detailed Description' section
762 * above has information about the issues to be taken into account if
763 * a call to this method is to be made.
764 * @param old_state Indicates the cancellation state of the calling
765 * thread immediately before this call to unblock() was made, either
766 * PTHREAD_CANCEL_DISABLE (if the thread was previously uncancellable)
767 * or PTHREAD_CANCEL_ENABLE (if this call did nothing because the
768 * thread was already cancellable).
769 * @return 0 if successful, else a value other than 0.
770 */
771 static int unblock(int& old_state) noexcept {return pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_state);}
772
773 /**
774 * Makes the thread cancellable while the CancelBlock object exists
775 * (when the CancelBlock object ceases to exist, cancellation state is
776 * returned to the state prior to it being constructed). It should
777 * only be called by the thread which created the CancelBlock object.
778 * This method will not throw. The 'Detailed Description' section
779 * above has information about the issues to be taken into account if
780 * a call to this method is to be made.
781 * @return 0 if successful, else a value other than 0.
782 */
783 static int unblock() noexcept {int old_state; return unblock(old_state);}
784
785 /**
786 * Restores cancellation state to the state it was in immediately
787 * before this CancelBlock object was constructed. It should only be
788 * called by the thread which created the CancelBlock object. This
789 * method will not throw.
790 * @param old_state Indicates the cancellation state of the calling
791 * thread immediately before this call to restore() was made, either
792 * PTHREAD_CANCEL_DISABLE (if the thread was previously uncancellable)
793 * or PTHREAD_CANCEL_ENABLE (if this thread was previously
794 * cancellable).
795 * @return 0 if successful, else a value other than 0.
796 */
797 int restore(int& old_state) noexcept {return pthread_setcancelstate(starting_state, &old_state);}
798
799 /**
800 * Restores cancellation state to the state it was in immediately
801 * before this CancelBlock object was constructed. It should only be
802 * called by the thread which created the CancelBlock object. This
803 * method will not throw.
804 * @return 0 if successful, else a value other than 0.
805 */
806 int restore() noexcept {int old_state; return restore(old_state);}
807
808 /**
809 * The constructor will not throw.
810 * @param blocking Whether the CancelBlock object should start in
811 * blocking mode. The 'Detailed Description' section above has
812 * information about the issues to be taken into account if 'false' is
813 * passed to this parameter.
814 */
815 CancelBlock(bool blocking = true);
816
817 /**
818 * The destructor will put the thread in the cancellation state that
819 * it was in immediately before the CancelBlock object was constructed
820 * (which might be blocking). It will not throw.
821 */
822 ~CancelBlock() {restore();}
823
824 /* Only has effect if --with-glib-memory-slices-compat or
825 * --with-glib-memory-slices-no-compat option picked */
826 CGU_GLIB_MEMORY_SLICES_FUNCS
827 };
828
829 /**
830 * @class Exit thread.h c++-gtk-utils/thread.h
831 * @brief A class which can be thrown to terminate the throwing
832 * thread.
833 *
834 * This class can be thrown (instead of calling pthread_exit()) when a
835 * thread wishes to terminate itself and also ensure stack unwinding,
836 * so that destructors of local objects are called. It is caught
837 * automatically by the implementation of Cgu::Thread::Thread::start()
838 * so that it will only terminate the thread throwing it and not the
839 * whole process. See the Cgu::Thread::Thread::cancel() method above,
840 * for use when a thread wishes to terminate another one, and the
841 * caveats on the use of Cgu::Thread::Thread::cancel().
842 *
843 * Do not throw a Cgu::Thread::Exit object in a program with more than
844 * one main loop in order to terminate one of the threads which has
845 * its own main loop. Instead, just cause its main loop to terminate
846 * by, say, calling g_main_loop_quit() on it.
847 */
848 class Exit {};
849
850 } // namespace Thread
851
852 } // namespace Cgu
853
854 #endif