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