c++-gtk-utils
thread.h
Go to the documentation of this file.
1 /* Copyright (C) 2005 to 2015 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>
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.x/4.x 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 only be called by one thread, which
215  * can be any thread other than the one represented by this Thread
216  * object. The result is undefined if the thread represented by this
217  * Thread object is or was detached or join() has already been called
218  * for it (a Thread::JoinableHandle object will however give a defined
219  * result in such cases for threads originally started as joinable).
220  * It does not throw.
221  */
222  void join() noexcept {pthread_join(thread, 0);}
223 
224 /**
225  * Detaches the thread represented by this Thread object where it is
226  * joinable, so as to make it unjoinable. The effect is undefined if
227  * the thread is already unjoinable (a Thread::JoinableHandle object
228  * will however give a defined result in such cases for threads
229  * originally started as joinable). It does not throw.
230  */
231  void detach() noexcept {pthread_detach(thread);}
232 
233 /**
234  * Specifies whether the calling thread is the same thread as is
235  * represented by this Thread object. The effect is undefined if the
236  * thread represented by this Thread object has both (a) already
237  * terminated and (b) been detached or had a call to join() made for
238  * it. Accordingly, if the user is not able to establish from the
239  * program logic whether the thread has terminated, the thread must be
240  * created as joinable and is_caller() must not be called after a call
241  * to detach() has been made or a call to join() has returned. A
242  * Thread::JoinableHandle object can used to ensure this. This method
243  * does not throw.
244  * @return Returns true if the caller is in the thread represented by
245  * this Thread object.
246  */
247  bool is_caller() noexcept {return pthread_equal(thread, pthread_self());}
248 
249 /**
250  * Starts a new thread. It can be called by any thread.
251  * @param cb A callback object (created by Callback::make(),
252  * Callback::make_ref() or Callback::lambda()) encapsulating the
253  * function to be executed by the new thread. The Thread object
254  * returned by this function will take ownership of the callback: it
255  * will automatically be deleted either by the new thread when it has
256  * finished with it, or by this method in the calling thread if the
257  * attempt to start a new thread fails (including if std::bad_alloc is
258  * thrown).
259  * @param joinable Whether the join() method may be called in relation
260  * to the new thread.
261  * @return A Thread object representing the new thread which has been
262  * started, held by a std::unique_ptr object as it has single
263  * ownership semantics. The std::unique_ptr object will be empty
264  * (that is std::unique_ptr<Cgu::Thread::Thread>::get() will return 0)
265  * if the thread did not start correctly, which would mean that memory
266  * is exhausted, the pthread thread limit has been reached or pthread
267  * has run out of other resources to start new threads.
268  * @exception std::bad_alloc This method might throw std::bad_alloc if
269  * memory is exhausted and the system throws in that case. (This
270  * exception will not be thrown if the library has been installed
271  * using the \--with-glib-memory-slices-no-compat configuration
272  * option: instead glib will terminate the program if it is unable to
273  * obtain memory from the operating system.) If this exception is
274  * thrown, the thread will not have started.
275  * @note 1. The thread will keep running even if the return value of
276  * start() goes out of scope (but it will no longer be possible to
277  * call any of the methods in this class for it, which is fine if the
278  * thread is not started as joinable and it is not intended to cancel
279  * it).
280  * @note 2. If the thread is started with the joinable attribute, the
281  * user must subsequently either call the join() or the detach()
282  * method, as otherwise a resource leak may occur (the destructor of
283  * this class does not call detach() automatically). Alternatively,
284  * the return value of this method can be passed to a
285  * Thread::JoinableHandle object which will do this automatically in
286  * the Thread::JoinableHandle object's destructor.
287  * @note 3. Any Thread::Exit exception thrown from the function
288  * executed by the new thread will be caught and consumed. The thread
289  * will safely terminate and unwind the stack in so doing.
290  * @note 4. If any uncaught exception other than Thread::Exit is
291  * allowed to propagate from the initial function executed by the new
292  * thread, the exception is not consumed (NPTL's forced stack
293  * unwinding on cancellation does not permit catching with an ellipsis
294  * argument without rethrowing, and even if it did permit it, the
295  * result would be an unreported error). The C++11 standard requires
296  * std::terminate() to be called in such a case and so the entire
297  * program terminated. Accordingly, a user must make sure that no
298  * exceptions, other than Thread::Exit or any cancellation
299  * pseudo-exception, can propagate from the initial function executed
300  * by the new thread. This includes ensuring that, for any argument
301  * passed to that function which is not a built-in type and which is
302  * not taken by the function by const or non-const reference, the
303  * argument type's copy constructor does not throw.
304  */
305  static std::unique_ptr<Cgu::Thread::Thread> start(const Cgu::Callback::Callback* cb,
306  bool joinable);
307 
308 /**
309  * Starts a new thread. It can be called by any thread.
310  * @param func A callable object, such as formed by a lambda
311  * expression or the result of std::bind, which will be executed by
312  * the new thread.
313  * @param joinable Whether the join() method may be called in relation
314  * to the new thread.
315  * @return A Thread object representing the new thread which has been
316  * started, held by a std::unique_ptr object as it has single
317  * ownership semantics. The std::unique_ptr object will be empty
318  * (that is std::unique_ptr<Cgu::Thread::Thread>::get() will return 0)
319  * if the thread did not start correctly, which would mean that memory
320  * is exhausted, the pthread thread limit has been reached or pthread
321  * has run out of other resources to start new threads.
322  * @exception std::bad_alloc This method might throw std::bad_alloc if
323  * memory is exhausted and the system throws in that case. (This
324  * exception will not be thrown if the library has been installed
325  * using the \--with-glib-memory-slices-no-compat configuration
326  * option: instead glib will terminate the program if it is unable to
327  * obtain memory from the operating system.) If this exception is
328  * thrown, the thread will not have started.
329  * @note 1. This function may also throw if the copy or move
330  * constructor of the callable object throws. If that happens, the
331  * thread will not have started.
332  * @note 2. The thread will keep running even if the return value of
333  * start() goes out of scope (but it will no longer be possible to
334  * call any of the methods in this class for it, which is fine if the
335  * thread is not started as joinable and it is not intended to cancel
336  * it).
337  * @note 3. If the thread is started with the joinable attribute, the
338  * user must subsequently either call the join() or the detach()
339  * method, as otherwise a resource leak may occur (the destructor of
340  * this class does not call detach() automatically). Alternatively,
341  * the return value of this method can be passed to a
342  * Thread::JoinableHandle object which will do this automatically in
343  * the Thread::JoinableHandle object's destructor.
344  * @note 4. Any Thread::Exit exception thrown from the function
345  * executed by the new thread will be caught and consumed. The thread
346  * will safely terminate and unwind the stack in so doing.
347  * @note 5. If any uncaught exception other than Thread::Exit is
348  * allowed to propagate from the initial function executed by the new
349  * thread, the exception is not consumed (NPTL's forced stack
350  * unwinding on cancellation does not permit catching with an ellipsis
351  * argument without rethrowing, and even if it did permit it, the
352  * result would be an unreported error). The C++11 standard requires
353  * std::terminate() to be called in such a case and so the entire
354  * program terminated. Accordingly, a user must make sure that no
355  * exceptions, other than Thread::Exit or any cancellation
356  * pseudo-exception, can propagate from the initial function executed
357  * by the new thread. This includes ensuring that, for any bound
358  * argument passed to that function which is not a built-in type and
359  * which is not taken by the function by const or non-const reference,
360  * the argument type's copy constructor does not throw.
361  *
362  * Since 2.1.0
363  */
364 // we need to use enable_if so that where this function is passed a
365 // pointer to non-const Callback::Callback, or some other convertible
366 // pointer, this templated overload is dropped from the overload set,
367 // in order to support the Callback::Callback pointer overloads of
368 // this function. This overload calls into the version of this
369 // function taking a pointer to const Callback::Callback in order to
370 // perform type erasure.
371  template <class F,
372  class = typename std::enable_if<!std::is_convertible<typename std::remove_reference<F>::type,
373  const Cgu::Callback::Callback*>::value>::type>
374  static std::unique_ptr<Cgu::Thread::Thread> start(F&& func,
375  bool joinable) {
376  return start(Cgu::Callback::lambda<>(std::forward<F>(func)), joinable);
377  }
378 
379 #ifdef CGU_USE_GLIB_MEMORY_SLICES_NO_COMPAT
381 #endif
382 };
383 
384 /**
385  * @class Cgu::Thread::JoinableHandle thread.h c++-gtk-utils/thread.h
386  * @brief A class wrapping a Thread::Thread object representing a
387  * joinable thread.
388  * @sa Thread::Thread Thread::Future
389  *
390  * This class enables a joinable thread to be made more easily
391  * exception safe. It can also be used to provide that a joinable
392  * thread is not detached or joined while other methods dependent on
393  * that might still be called, and to provide a defined result where
394  * there are multiple calls to join() and/or detach(). When it is
395  * destroyed, it will either detach or join the thread represented by
396  * the wrapped Thread::Thread object unless it has previously been
397  * detached or joined using the detach() or join() methods, so
398  * avoiding thread resource leaks. Whether it will detach() or join()
399  * on destruction depends on the Thread::JoinableHandle::Action
400  * argument passed to the
401  * Thread::JoinableHandle::JoinableHandle(std::unique_ptr<Thread::Thread>,
402  * Action) constructor.
403  *
404  * Passing Thread::JoinableHandle::detach_on_exit to that argument is
405  * not always the correct choice where the thread callback has been
406  * bound to a reference argument in local scope and an exception might
407  * be thrown, because the thread will keep running after the
408  * Thread::JoinableHandle object and other local variables have
409  * (because of the exception) gone out of scope. Consider the
410  * following trivial parallelized calculation example:
411  *
412  * @code
413  * std::vector<int> get_readings();
414  * void get_mean(const std::vector<int>& v, int& result);
415  * void get_std_deviation(const std::vector<int>& v, int& result); // might throw
416  * void show_result(int mean, int deviation);
417  *
418  * using namespace Cgu;
419  * void do_calc() {
420  * int i, j;
421  * std::vector<int> v = get_readings();
422  * std::unique_ptr<Thread::Thread> t =
423  * Thread::Thread::start(std::bind(&get_mean, std::cref(v), std::ref(i)), true);
424  * if (t.get()) { // checks whether thread started correctly
425  * get_std_deviation(v, j);
426  * t->join();
427  * show_result(i, j);
428  * }
429  * }
430  * @endcode
431  *
432  * If get_std_deviation() throws, as well as there being a potential
433  * thread resource leak by virtue of no join being made, the thread
434  * executing get_mean() will continue running and attempt to access
435  * variable v, and put its result in variable i, which may by then
436  * both be out of scope. To deal with such a case, the thread could
437  * be wrapped in a Thread::JoinableHandle object which joins on exit
438  * rather than detaches, for example:
439  *
440  * @code
441  * ...
442  * using namespace Cgu;
443  * void do_calc() {
444  * int i, j;
445  * std::vector<int> v = get_readings();
446  * Thread::JoinableHandle t{Thread::Thread::start(std::bind(&get_mean, std::cref(v), std::ref(i)), true),
447  * Thread::JoinableHandle::join_on_exit};
448  * if (t.is_managing()) { // checks whether thread started correctly
449  * get_std_deviation(v, j);
450  * t.join();
451  * show_result(i, j);
452  * }
453  * }
454  * @endcode
455  *
456  * Better still, however, would be to use Cgu::Thread::Future in this
457  * kind of usage, namely a usage where a worker thread is intended to
458  * provide a result for inspection.
459  *
460  * @note These examples assume that the std::vector library
461  * implementation permits concurrent reads of a vector object by
462  * different threads. Whether that is the case depends on the
463  * documentation of the library concerned (if designed for a
464  * multi-threaded environment, most will permit this, and it is
465  * required for a fully conforming C++11 library implementation).
466  */
468 public:
470 
471 private:
472  Mutex mutex; // make this the first member so the constructors are strongly exception safe
473  Action action;
474  bool detached;
475  std::unique_ptr<Cgu::Thread::Thread> thread;
476 
477 public:
478 /**
479  * Cancels the thread represented by the wrapped Thread::Thread
480  * object. It can be called by any thread. The effect is undefined
481  * if when called the thread represented by the wrapped Thread::Thread
482  * object has both (a) already terminated and (b) had a call to join()
483  * or detach() made for it. Accordingly, if the user is not able to
484  * establish from the program logic whether the thread has terminated,
485  * cancel() must not be called after a call to detach() has been made
486  * or a call to join() has returned: this can be ensured by only
487  * detaching or joining via this object's destructor (that is, by not
488  * using the explicit detach() and join() methods). This method does
489  * not throw.
490  * @note Use this method with care - see Thread::cancel() for further
491  * information.
492  */
493  void cancel();
494 
495 /**
496  * Joins the thread represented by the wrapped Thread::Thread object
497  * (that is, waits for it to terminate), unless the detach() or join()
498  * method has previously been called in which case this call does
499  * nothing. It can be called by any thread other than the one
500  * represented by the wrapped Thread::Thread object, but only one
501  * thread can wait on it: if one thread (thread A) calls it while
502  * another thread (thread B) is already blocking on it, thread A's
503  * call to this method will return immediately and return false. It
504  * does not throw.
505  * @return true if a successful join() has been accomplished (that is,
506  * detach() or join() have not previously been called), otherwise
507  * false.
508  */
509  bool join();
510 
511 /**
512  * Detaches the thread represented by this Thread::Thread object, so
513  * as to make it unjoinable, unless the detach() or join() method has
514  * previously been called in which case this call does nothing. It
515  * does not throw.
516  */
517  void detach();
518 
519 /**
520  * Specifies whether the calling thread is the same thread as is
521  * represented by the wrapped Thread::Thread object. It can be called
522  * by any thread. The effect is undefined if the thread represented
523  * by the wrapped Thread::Thread object has both (a) already
524  * terminated and (b) had a call to join() or detach() made for it.
525  * Accordingly, if the user is not able to establish from the program
526  * logic whether the thread has terminated, is_caller() must not be
527  * called after a call to detach() has been made or a call to join()
528  * has returned: this can be ensured by only detaching or joining via
529  * this object's destructor (that is, by not using the explicit
530  * detach() and join() methods). This method does not throw.
531  * @return Returns true if the caller is in the thread represented by
532  * the wrapped Thread::Thread object. If not, or this JoinableHandle
533  * does not wrap any Thread object, then returns false.
534  */
535  bool is_caller();
536 
537 /**
538  * Specifies whether this JoinableHandle object has been initialized
539  * with a Thread::Thread object representing a correctly started
540  * thread in respect of which neither JoinableHandle::detach() nor
541  * JoinableHandle::join() has been called. It can be called by any
542  * thread. It is principally intended to enable the constructor
543  * taking a std::unique_ptr<Cgu::Thread::Thread> object to be directly
544  * initialized by a call to Thread::Thread::start(), by providing a
545  * means for the thread calling Thread::Thread::start() to check
546  * afterwards that the new thread did, in fact, start correctly. Note
547  * that this method will return true even after the thread has
548  * finished, provided neither the join() nor detach() method has been
549  * called.
550  * @return Returns true if this object has been initialized by a
551  * Thread::Thread object representing a correctly started thread in
552  * respect of which neither JoinableHandle::detach() nor
553  * JoinableHandle::join() has been called, otherwise false.
554  */
555  bool is_managing();
556 
557 /**
558  * Moves one JoinableHandle object to another JoinableHandle object.
559  * This is a move operation which transfers ownership to the assignee,
560  * as the handles store their Thread::Thread object by
561  * std::unique_ptr<>. Any existing thread managed by the assignee
562  * prior to the move will be detached if it has not already been
563  * detached or joined. This method will not throw.
564  * @param h The assignor/movant, which will cease to hold a valid
565  * Thread::Thread object after the move has taken place.
566  * @return A reference to the assignee JoinableHandle object after
567  * assignment.
568  * @note This method is thread safe as regards the assignee (the
569  * object assigned to), but no synchronization is carried out with
570  * respect to the rvalue assignor/movant. This is because temporaries
571  * are only visible and accessible in the thread carrying out the move
572  * operation and synchronization for them would represent pointless
573  * overhead. In a case where the user uses std::move to force a move
574  * from a named object, and that named object's lifetime is managed by
575  * (or the object is otherwise accessed by) a different thread than
576  * the one making the move, the user must carry out her own
577  * synchronization with respect to that different thread, as the named
578  * object will be mutated by the move.
579  */
581 
582 /**
583  * This constructor initializes a new JoinableHandle object with a
584  * std::unique_ptr<Thread::Thread> object, as provided by
585  * Thread::Thread::start(). This is a move operation which transfers
586  * ownership to the new object.
587  * @param thr The initializing Thread::Thread object (which must have
588  * been created as joinable) passed by a std::unique_ptr smart
589  * pointer. This is a move operation.
590  * @param act Either Thread::JoinableHandle::detach_on_exit (which
591  * will cause the destructor to detach the thread if it has not
592  * previously been detached or joined) or
593  * Thread::JoinableHandle::join_on_exit (which will cause the
594  * destructor to join the thread if it has not previously been
595  * detached or joined).
596  * @exception Cgu::Thread::MutexError Throws this exception if
597  * initialization of the internal mutex fails. The constructor is
598  * strongly exception safe: if Cgu::Thread::MutexError is thrown, the
599  * initializing std::unique_ptr<Cgu::Thread::Thread> object will be
600  * left unchanged. (It is often not worth checking for this
601  * exception, as it means either memory is exhausted or pthread has
602  * run out of other resources to create new mutexes.)
603  * @note 1. It is not necessary to check that the thread parameter
604  * represents a correctly started thread (that is, that thr.get() does
605  * not return 0) before this constructor is invoked, because that can
606  * be done after construction by calling JoinableHandle::is_managing()
607  * (a JoinableHangle object can safely handle a case where thr.get()
608  * does return 0). This enables a JoinableHandle object to be
609  * directly initialized by this constructor from a call to
610  * Thread::Thread::start().
611  * @note 2. No synchronization is carried out with respect to the
612  * initializing std::unique_ptr object. This is because such an
613  * object is usually passed to this constructor as a temporary, which
614  * is only visible and accessible in the thread carrying out the move
615  * operation, in which case synchronization would represent pointless
616  * overhead. In a case where the user uses std::move to force a move
617  * from a named std::unique_ptr object, and that named object's
618  * lifetime is managed by (or the object is otherwise accessed by) a
619  * different thread than the one making the move, the user must carry
620  * out her own synchronization with respect to that different thread,
621  * as the initializing std::unique_ptr object will be mutated by the
622  * move.
623  * @sa JoinableHandle::is_managing().
624  */
625  JoinableHandle(std::unique_ptr<Cgu::Thread::Thread> thr, Action act): action(act), detached(false), thread(std::move(thr)) {}
626 
627 /**
628  * This constructor initializes a new JoinableHandle object with an
629  * existing JoinableHandle object. This is a move operation which
630  * transfers ownership to the new object.
631  * @param h The initializing JoinableHandle object, which will cease
632  * to hold a valid Thread::Thread object after the initialization has
633  * taken place.
634  * @exception Cgu::Thread::MutexError Throws this exception if
635  * initialization of the internal mutex fails. The constructor is
636  * strongly exception safe: if Cgu::Thread::MutexError is thrown, the
637  * initializing Cgu::Thread::JoinableHandle object will be left
638  * unchanged. (It is often not worth checking for this exception, as
639  * it means either memory is exhausted or pthread has run out of other
640  * resources to create new mutexes.)
641  * @note No synchronization is carried out with respect to the
642  * initializing rvalue. This is because temporaries are only visible
643  * and accessible in the thread carrying out the move operation and
644  * synchronization for them would represent pointless overhead. In a
645  * case where a user uses std::move to force a move from a named
646  * object, and that named object's lifetime is managed by (or the
647  * object is otherwise accessed by) a different thread than the one
648  * making the move, the user must carry out her own synchronization
649  * with respect to that different thread, as the named object will be
650  * mutated by the move.
651  */
652  JoinableHandle(JoinableHandle&& h): action(h.action), detached(h.detached), thread(std::move(h.thread)) {}
653 
654 /**
655  * The default constructor. Nothing is managed until the move
656  * assignment operator has been called.
657  * @exception Cgu::Thread::MutexError Throws this exception if
658  * initialization of the internal mutex fails. (It is often not worth
659  * checking for this exception, as it means either memory is exhausted
660  * or pthread has run out of other resources to create new mutexes.)
661  *
662  * Since 2.0.8
663  */
664  JoinableHandle(): action(detach_on_exit), detached(true) {}
665 
666 /**
667  * The destructor will detach a managed thread (if the
668  * Thread::JoinableHandle::detach_on_exit flag is set) or join it (if
669  * the Thread::JoinableHandle::join_on_exit flag is set), unless it
670  * has previously been detached or joined with the detach() or join()
671  * methods. The destructor is thread safe (any thread may destroy the
672  * JoinableHandle object). The destructor will not throw.
673  */
674  ~JoinableHandle();
675 
676 /* Only has effect if --with-glib-memory-slices-compat or
677  * --with-glib-memory-slices-no-compat option picked */
679 };
680 
681 /**
682  * @class CancelBlock thread.h c++-gtk-utils/thread.h
683  * @brief A class enabling the cancellation state of a thread to be
684  * controlled.
685  *
686  * A class enabling the cancellation state of a thread to be
687  * controlled, so as to provide exception safe cancellation state
688  * changes. When a CancelBlock object goes out of scope, the thread's
689  * cancellation state is returned to the state it was in immediately
690  * prior to the object's construction.
691  *
692  * Cancellation state can be changed before a CancelBlock object goes
693  * out of scope by calling its block() and unblock() methods.
694  * However, care should be taken if calling unblock() for the purpose
695  * of enabling thread cancellation while the CancelBlock object is
696  * still in existence: this should normally only be done if the
697  * thread's cancellation state at the time the CancelBlock object was
698  * constructed (which is the cancellation state to which the thread
699  * will be restored when the object goes out of scope) was
700  * PTHREAD_CANCEL_DISABLE. This is because when a thread begins
701  * cancellation the POSIX standard states that it will automatically
702  * switch itself into a PTHREAD_CANCEL_DISABLE state (see System
703  * Interfaces, section 2.9.5, Thread Cancellation Cleanup Handlers),
704  * and the POSIX standard further states that the behaviour is
705  * undefined if a cancellation handler attempts to enable cancellation
706  * again while the thread is cleaning up - and any thread
707  * implementation such as NPTL which unwinds the stack on cancellation
708  * will do so if the CancelBlock's destructor would restore to
709  * PTHREAD_CANCEL_ENABLE state. Whilst it is to be expected that any
710  * cancellation stack unwinding implementation will behave sensibly in
711  * these circumstances, this is not mandated by POSIX, so making code
712  * relying on this less portable.
713  *
714  * For these reasons, the same care should be exercised if passing
715  * 'false' to the CancelBlock constructor's 'blocking' argument.
716  */
717 
718 class CancelBlock {
719  int starting_state;
720 public:
721 /**
722  * This class cannot be copied. The copy constructor is deleted.
723  */
724  CancelBlock(const CancelBlock&) = delete;
725 
726 /**
727  * This class cannot be copied. The assignment operator is deleted.
728  */
729  CancelBlock& operator=(const CancelBlock&) = delete;
730 
731 /**
732  * Makes the thread uncancellable, even if the code passes through a
733  * cancellation point, while the CancelBlock object exists (when the
734  * CancelBlock object ceases to exist, cancellation state is returned
735  * to the state prior to it being constructed). It should only be
736  * called by the thread which created the CancelBlock object. This
737  * method will not throw.
738  * @param old_state Indicates the cancellation state of the calling
739  * thread immediately before this call to block() was made, either
740  * PTHREAD_CANCEL_ENABLE (if the thread was previously cancellable) or
741  * PTHREAD_CANCEL_DISABLE (if this call did nothing because the thread
742  * was already uncancellable).
743  * @return 0 if successful, else a value other than 0.
744  */
745  static int block(int& old_state) noexcept {return pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);}
746 
747 /**
748  * Makes the thread uncancellable, even if the code passes through a
749  * cancellation point, while the CancelBlock object exists (when the
750  * CancelBlock object ceases to exist, cancellation state is returned
751  * to the state prior to it being constructed). It should only be
752  * called by the thread which created the CancelBlock object. This
753  * method will not throw.
754  * @return 0 if successful, else a value other than 0.
755  */
756  static int block() noexcept {int old_state; return block(old_state);}
757 
758 /**
759  * Makes the thread cancellable while the CancelBlock object exists
760  * (when the CancelBlock object ceases to exist, cancellation state is
761  * returned to the state prior to it being constructed). It should
762  * only be called by the thread which created the CancelBlock object.
763  * This method will not throw. The 'Detailed Description' section
764  * above has information about the issues to be taken into account if
765  * a call to this method is to be made.
766  * @param old_state Indicates the cancellation state of the calling
767  * thread immediately before this call to unblock() was made, either
768  * PTHREAD_CANCEL_DISABLE (if the thread was previously uncancellable)
769  * or PTHREAD_CANCEL_ENABLE (if this call did nothing because the
770  * thread was already cancellable).
771  * @return 0 if successful, else a value other than 0.
772  */
773  static int unblock(int& old_state) noexcept {return pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_state);}
774 
775 /**
776  * Makes the thread cancellable while the CancelBlock object exists
777  * (when the CancelBlock object ceases to exist, cancellation state is
778  * returned to the state prior to it being constructed). It should
779  * only be called by the thread which created the CancelBlock object.
780  * This method will not throw. The 'Detailed Description' section
781  * above has information about the issues to be taken into account if
782  * a call to this method is to be made.
783  * @return 0 if successful, else a value other than 0.
784  */
785  static int unblock() noexcept {int old_state; return unblock(old_state);}
786 
787 /**
788  * Restores cancellation state to the state it was in immediately
789  * before this CancelBlock object was constructed. It should only be
790  * called by the thread which created the CancelBlock object. This
791  * method will not throw.
792  * @param old_state Indicates the cancellation state of the calling
793  * thread immediately before this call to restore() was made, either
794  * PTHREAD_CANCEL_DISABLE (if the thread was previously uncancellable)
795  * or PTHREAD_CANCEL_ENABLE (if this thread was previously
796  * cancellable).
797  * @return 0 if successful, else a value other than 0.
798  */
799  int restore(int& old_state) noexcept {return pthread_setcancelstate(starting_state, &old_state);}
800 
801 /**
802  * Restores cancellation state to the state it was in immediately
803  * before this CancelBlock object was constructed. It should only be
804  * called by the thread which created the CancelBlock object. This
805  * method will not throw.
806  * @return 0 if successful, else a value other than 0.
807  */
808  int restore() noexcept {int old_state; return restore(old_state);}
809 
810 /**
811  * The constructor will not throw.
812  * @param blocking Whether the CancelBlock object should start in
813  * blocking mode. The 'Detailed Description' section above has
814  * information about the issues to be taken into account if 'false' is
815  * passed to this parameter.
816  */
817  CancelBlock(bool blocking = true);
818 
819 /**
820  * The destructor will put the thread in the cancellation state that
821  * it was in immediately before the CancelBlock object was constructed
822  * (which might be blocking). It will not throw.
823  */
825 
826 /* Only has effect if --with-glib-memory-slices-compat or
827  * --with-glib-memory-slices-no-compat option picked */
829 };
830 
831 /**
832  * @class Exit thread.h c++-gtk-utils/thread.h
833  * @brief A class which can be thrown to terminate the throwing
834  * thread.
835  *
836  * This class can be thrown (instead of calling pthread_exit()) when a
837  * thread wishes to terminate itself and also ensure stack unwinding,
838  * so that destructors of local objects are called. It is caught
839  * automatically by the implementation of Cgu::Thread::Thread::start()
840  * so that it will only terminate the thread throwing it and not the
841  * whole process. See the Cgu::Thread::Thread::cancel() method above,
842  * for use when a thread wishes to terminate another one, and the
843  * caveats on the use of Cgu::Thread::Thread::cancel().
844  *
845  * Do not throw a Cgu::Thread::Exit object in a program with more than
846  * one main loop in order to terminate one of the threads which has
847  * its own main loop. Instead, just cause its main loop to terminate
848  * by, say, calling g_main_loop_quit() on it.
849  */
850 class Exit {};
851 
852 } // namespace Thread
853 
854 } // namespace Cgu
855 
856 #endif
Action
Definition: thread.h:469
static std::unique_ptr< Cgu::Thread::Thread > start(F &&func, bool joinable)
Definition: thread.h:374
CancelBlock & operator=(const CancelBlock &)=delete
static int block() noexcept
Definition: thread.h:756
int restore(int &old_state) noexcept
Definition: thread.h:799
bool is_caller() noexcept
Definition: thread.h:247
STL namespace.
JoinableHandle(std::unique_ptr< Cgu::Thread::Thread > thr, Action act)
Definition: thread.h:625
void detach() noexcept
Definition: thread.h:231
This file provides classes for type erasure.
A class wrapping a Thread::Thread object representing a joinable thread.
Definition: thread.h:467
void join() noexcept
Definition: thread.h:222
A class enabling the cancellation state of a thread to be controlled.
Definition: thread.h:718
A class which can be thrown to terminate the throwing thread.
Definition: thread.h:850
A wrapper class for pthread mutexes.
Definition: mutex.h:117
~CancelBlock()
Definition: thread.h:824
CancelBlock(const CancelBlock &)=delete
A class representing a pthread thread.
Definition: thread.h:166
Provides wrapper classes for pthread mutexes and condition variables, and scoped locking classes for ...
Definition: application.h:44
static int unblock() noexcept
Definition: thread.h:785
JoinableHandle(JoinableHandle &&h)
Definition: thread.h:652
Thread & operator=(const Thread &)=delete
JoinableHandle()
Definition: thread.h:664
int restore() noexcept
Definition: thread.h:808
void cancel() noexcept
Definition: thread.h:210
static std::unique_ptr< Cgu::Thread::Thread > start(const Cgu::Callback::Callback *cb, bool joinable)
JoinableHandle & operator=(JoinableHandle &&h)
The callback interface class.
Definition: callback.h:567
#define CGU_GLIB_MEMORY_SLICES_FUNCS
Definition: cgu_config.h:84
static int block(int &old_state) noexcept
Definition: thread.h:745
static int unblock(int &old_state) noexcept
Definition: thread.h:773