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