/usr/include/cwidget/generic/threads/threads.h is in libcwidget-dev 0.5.17-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 | // threads.h -*-c++-*-
//
// Copyright (C) 2005-2009 Daniel Burrows
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; see the file COPYING. If not, write to
// the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
// A simple thread wrapper library. I'm not using the existing ones
// in order to keep aptitude's dependency count low (as long as I
// don't need too much out of it, this should be fairly
// simple..right?). The API was inspired by that of boost::threads.
#ifndef THREADS_H
#define THREADS_H
#include <errno.h>
#include <cwidget/generic/util/exception.h>
namespace cwidget
{
/** \brief C++ wrappers for the POSIX threading primitives.
*
* These provide Resource-Allocation-Is-Initialization semantics
* and are loosely modelled on the Boost threads library.
*/
namespace threads
{
/** The base class for all thread-related exceptions. */
class ThreadException : public util::Exception
{
};
/** Thrown when thread creation fails; according to
* pthread_create(3), this only occurs if there aren't enough
* system resources to create a thread.
*/
class ThreadCreateException : public ThreadException
{
int errnum;
public:
ThreadCreateException(int error)
: errnum(error)
{
}
int get_errnum() const { return errnum; }
std::string errmsg() const;
};
/** Thrown when thread::join fails. */
class ThreadJoinException : public ThreadException
{
std::string reason;
int errnum;
public:
ThreadJoinException(const int error);
int get_errnum() const { return errnum; }
std::string errmsg() const;
};
/** \brief Thrown when the mutex being used to wait on a condition
* is not locked.
*
* The mutex must be locked to preserve atomicity.
*/
class ConditionNotLockedException : public ThreadException
{
public:
std::string errmsg() const;
};
/** \brief Thrown when an error-checking mutex is locked twice. */
class DoubleLockException : public ThreadException
{
public:
std::string errmsg() const;
};
/** \brief A system thread.
*
* This class represents a single thread of control. It is
* conceptually based on the Boost thread class; like the Boost
* thread class, it is non-copyable.
*/
class thread
{
pthread_t tid;
bool joined;
thread(const thread &other);
thread &operator=(const thread &other);
template<typename F>
static void *bootstrap(void *p)
{
F thunk(*((F *) p));
delete ((F *) p);
thunk();
return 0;
}
public:
/** \brief Stores the attributes with which a thread is to be
* created.
*
* This wraps pthread_attr_t. To use this class, create an
* instance and then invoke the set_* methods to set the
* desired attributes. Pass the final attributes structure to
* thread::thread.
*/
class attr
{
pthread_attr_t attrs;
friend class thread;
public:
attr()
{
pthread_attr_init(&attrs);
}
// All attributes except detach state can be manipulated (detach
// state is left at PTHREAD_CREATE_JOINABLE).
void set_inherit_sched(int i)
{
pthread_attr_setinheritsched(&attrs, i);
}
int get_inherit_sched() const
{
int rval;
pthread_attr_getinheritsched(&attrs, &rval);
return rval;
}
void set_sched_param(const sched_param &sp)
{
pthread_attr_setschedparam(&attrs, &sp);
}
sched_param get_sched_param() const
{
sched_param rval;
pthread_attr_getschedparam(&attrs, &rval);
return rval;
}
void set_sched_policy(int p)
{
pthread_attr_setschedpolicy(&attrs, p);
}
int get_sched_policy() const
{
int rval;
pthread_attr_getschedpolicy(&attrs, &rval);
return rval;
}
void set_scope(int p)
{
pthread_attr_setscope(&attrs, p);
}
int get_scope() const
{
int rval;
pthread_attr_getscope(&attrs, &rval);
return rval;
}
~attr()
{
pthread_attr_destroy(&attrs);
}
};
/** \brief Create a new thread.
*
* The new thread will begin execution by calling operator() on
* a copy of the given function object.
*
* \param thunk a function object of no parameters that will
* be invoked to start this thread. Must be copyable.
*
* \param a the attributes with which to create the new thread.
*/
template<typename F>
thread(const F &thunk, const attr &a = attr())
:joined(false)
{
// Create a thunk on the heap to pass to the new thread.
F *tmp = new F(thunk);
if(pthread_create(&tid, &a.attrs, &thread::bootstrap<F>, tmp) != 0)
{
int errnum = errno;
delete tmp;
throw ThreadCreateException(errnum);
}
}
~thread()
{
if(!joined)
pthread_detach(tid);
}
/** Wait for this thread to finish. */
void join()
{
int rval = pthread_join(tid, NULL);
if(rval != 0)
throw ThreadJoinException(rval);
else
joined = true;
}
/** Cancel this thread. */
void cancel()
{
pthread_cancel(tid);
}
};
/** \brief Wrap noncopyable objects to bootstrap threads.
*
* Stores a reference to a noncopyable nullary function object in
* a structure that is suitable as a bootstrap function for a
* thread.
*
* The contained object is assumed to last for as long as the
* thread does, and will not be (automatically) deleted or
* destroyed when the thread terminates.
*
* \param F the functor type that this structure wraps.
*/
template<typename F>
struct noncopy_bootstrap
{
F &f;
public:
/** \brief Create a noncopyable bootstrap wrapper.
*
* \param _f the function object to wrap.
*/
noncopy_bootstrap(F &_f)
:f(_f)
{
}
/** \brief Invoke F::operator() on the wrapped object. */
void operator()()
{
f();
}
};
class condition;
// The mutex abstraction
class mutex
{
public:
class lock;
class try_lock;
private:
pthread_mutex_t m;
friend class lock;
friend class try_lock;
// Conditions need to look inside mutexes and locks to find the
// real mutex object so the underlying thread library can do an
// atomic unlock-and-wait.
friend class condition;
mutex(const mutex &other);
mutex &operator=(const mutex &other);
public:
/** A mutex attributes object. */
class attr
{
pthread_mutexattr_t attrs;
friend class mutex;
public:
attr()
{
pthread_mutexattr_init(&attrs);
}
attr(int kind)
{
pthread_mutexattr_init(&attrs);
pthread_mutexattr_settype(&attrs, kind);
}
~attr()
{
pthread_mutexattr_destroy(&attrs);
}
int settype(int kind)
{
return pthread_mutexattr_settype(&attrs, kind);
}
int gettype()
{
int rval;
pthread_mutexattr_gettype(&attrs, &rval);
return rval;
}
};
/** Represents a lock on a mutex. Can be released and re-asserted
* as desired; when the lock goes out of scope, it will
* automatically be released if necessary.
*/
class lock
{
mutex &parent;
bool locked;
friend class condition;
lock(const lock &other);
lock &operator=(const lock &other);
public:
lock(mutex &_parent)
:parent(_parent), locked(false)
{
acquire();
}
/** Lock the associated mutex. */
void acquire()
{
if(locked)
throw DoubleLockException();
pthread_mutex_lock(&parent.m);
locked = true;
}
/** Unlock the associated mutex. */
void release()
{
pthread_mutex_unlock(&parent.m);
locked = false;
}
bool get_locked() const
{
return locked;
}
~lock()
{
if(locked)
pthread_mutex_unlock(&parent.m);
}
};
/** Represents a non-blocking lock on a mutex. */
class try_lock
{
mutex &parent;
bool locked;
friend class condition;
try_lock(const try_lock &other);
try_lock &operator=(const try_lock &other);
public:
try_lock(mutex &_parent)
:parent(_parent)
{
acquire();
}
~try_lock()
{
if(locked)
pthread_mutex_unlock(&parent.m);
}
void acquire()
{
if(locked)
throw DoubleLockException();
locked = pthread_mutex_trylock(&parent.m);
}
void release()
{
pthread_mutex_unlock(&parent.m);
locked = false;
}
bool get_locked() const
{
return locked;
}
};
mutex()
{
pthread_mutex_init(&m, NULL);
}
mutex(const attr &a)
{
pthread_mutex_init(&m, &a.attrs);
}
~mutex()
{
pthread_mutex_destroy(&m);
}
};
/** A mutex that is initialized to be recursive. Used because
* apparently C++ global constructors can't take arguments.
*/
class recursive_mutex : public mutex
{
public:
recursive_mutex()
:mutex(attr(PTHREAD_MUTEX_RECURSIVE))
{
}
};
/** A abstraction over conditions. When a condition variable is
* destroyed, any threads that are still blocked on it are woken
* up.
*/
class condition
{
pthread_cond_t cond;
public:
condition()
{
pthread_cond_init(&cond, NULL);
}
~condition()
{
// Wakey wakey
pthread_cond_broadcast(&cond);
pthread_cond_destroy(&cond);
}
void wake_one()
{
pthread_cond_signal(&cond);
}
void wake_all()
{
pthread_cond_broadcast(&cond);
}
/** Wait with the given guard (should be a lock type that is a
* friend of this condition object).
*
* This is a cancellation point. If the thread is cancelled
* while waiting on the condition, the mutex will be unlocked.
*/
template<typename Lock>
void wait(const Lock &l)
{
if(!l.get_locked())
throw ConditionNotLockedException();
pthread_cleanup_push((void (*)(void*))pthread_mutex_unlock, &l.parent.m);
pthread_cond_wait(&cond, &l.parent.m);
pthread_cleanup_pop(0);
}
/** Wait until the given predicate returns \b true.
*
* This is a cancellation point. If the thread is cancelled
* while waiting on the condition, the mutex will be unlocked.
* This does not apply to the predicate; it is responsible for
* cleaning up the mutex itself if the thread is cancelled
* while it is running.
*/
template<typename Lock, typename Pred>
void wait(const Lock &l, Pred p)
{
if(!l.get_locked())
throw ConditionNotLockedException();
while(!p())
wait(l);
}
/** Wait until either the condition is signalled or until the
* given time.
*
* This is a cancellation point. If the thread is cancelled
* while waiting on the condition, the mutex will be unlocked.
* This does not apply to the predicate; it is responsible for
* cleaning up the mutex itself if the thread is cancelled
* while it is running.
*
* \param l the guard of the condition
* \param until the time at which the wait should terminate
*
* \return \b true if the condition occurred or \b false if time
* ran out.
*/
template<typename Lock>
bool timed_wait(const Lock &l, const timespec &until)
{
if(!l.get_locked())
throw ConditionNotLockedException();
int rval;
pthread_cleanup_push((void(*)(void *))&pthread_mutex_unlock, &l.parent.m);
while((rval = pthread_cond_timedwait(&cond, &l.parent.m, &until)) == EINTR)
;
pthread_cleanup_pop(0);
return rval != ETIMEDOUT;
}
/** Wait either until the condition is signalled while the given
* predicate is \b true or until the given time.
*
* This is a cancellation point. If the thread is cancelled
* while waiting on the condition mutex will be unlocked. If
* the thread is cancelled while invoking the predicate, no
* guarantees are made by this routine; if the predicate
* invokes a cancellation point, it is responsible for pushing
* a cleanup handler.
*/
template<typename Lock, typename Pred>
bool timed_wait(const Lock &l, const timespec &until, const Pred &p)
{
if(!l.get_locked())
throw ConditionNotLockedException();
while(!p())
{
if(!timed_wait(l, until))
return false;
}
return true;
}
};
/** A higher-level abstraction borrowed from Concurrent Haskell,
* which borrowed it from another language I forget. This
* represents a "box" that can either hold a value or be empty.
* Any thread can take the current value of the box or place a new
* value inside it; the attempt will block until a value is
* available or the box is empty, respectively. It's sort of a
* single-element bounded communications channel.
*
* The value in the box is stored with copying semantics. Like the
* other threading primitives, boxes are not copyable.
*/
template<typename T>
class box
{
T val;
bool filled;
condition cond;
mutex m;
box(const box &other);
box &operator=(const box &other);
public:
/** Create an empty box. */
box()
:filled(false)
{
}
/** Create a box containing the given value. */
box(const T &_val)
:val(_val), filled(true)
{
}
/** Retrieve the current value of this box. If the box is empty,
* block until it is full.
*/
T take();
/** Fill this box with a value. If the box is full, block until
* it is empty.
*/
void put(const T &t);
/** If there is a value in the box, retrieve it immediately;
* otherwise do nothing.
*
* \param out the location in which the value should be stored
* \return \b true iff a value was found in the box
*/
bool try_take(T &out);
/** If the box is empty, place a value in it; otherwise, do
* nothing.
*
* \param t the value to place in the box
*
* \return \b true iff the box was empty (and hence was filled
* with t)
*/
bool try_put(const T &t);
/** As try_take(), but wait for the given amount of time before
* giving up.
*/
bool timed_take(T &out, const timespec &until);
/** As try_put(), but wait for the given amount of time before
* giving up.
*/
bool timed_put(const T &t, const timespec &until);
/** Atomically modify the contents of the box; if an exception is
* thrown by the given function object, no action will be
* performed.
*/
template<typename Mutator>
void update(const Mutator &m);
};
/** A box specialized for 'void'; may make it easier to write
* other templated classes. Could maybe just be a mutex, but I
* don't think you can quite mimic the box API that way.
*/
template<>
class box<void>
{
bool filled;
mutex m;
condition cond;
public:
box()
:filled(false)
{
}
box(bool _filled)
:filled(_filled)
{
}
void take();
void put();
bool try_take();
bool try_put();
bool timed_take(const timespec &until);
bool timed_put(const timespec &until);
template<typename Mutator>
void update(const Mutator &m)
{
take();
try
{
m();
}
catch(...)
{
put();
throw;
}
put();
}
};
/** Internal helper struct. */
struct bool_ref_pred
{
const bool &b;
public:
bool_ref_pred(const bool &_b)
:b(_b)
{
}
bool operator()() const
{
return b;
}
};
/** Internal helper struct. */
struct not_bool_ref_pred
{
const bool &b;
public:
not_bool_ref_pred(const bool &_b)
:b(_b)
{
}
bool operator()() const
{
return !b;
}
};
template<typename T>
inline
T box<T>::take()
{
mutex::lock l(m);
cond.wait(l, bool_ref_pred(filled));
filled = false;
// Interesting question: does l get released before or after the
// copy? To be safe, I explicitly copy before I return.
T rval = val;
return rval;
}
inline
void box<void>::take()
{
mutex::lock l(m);
cond.wait(l, bool_ref_pred(filled));
filled = false;
}
template<typename T>
inline
bool box<T>::try_take(T &out)
{
mutex::lock l(m);
if(filled)
{
filled = false;
out = val;
return true;
}
else
return false;
}
inline
bool box<void>::try_take()
{
mutex::lock l(m);
if(filled)
{
filled = false;
return true;
}
else
return false;
}
template<typename T>
inline
bool box<T>::timed_take(T &out, const timespec &until)
{
mutex::lock l(m);
if(cond.timed_wait(l, until, bool_ref_pred(filled)))
{
filled = false;
out = val;
return true;
}
else
return false;
}
inline
bool box<void>::timed_take(const timespec &until)
{
mutex::lock l(m);
if(cond.timed_wait(l, until, bool_ref_pred(filled)))
{
filled = false;
return true;
}
else
return false;
}
template<typename T>
inline
void box<T>::put(const T &new_val)
{
mutex::lock l(m);
cond.wait(l, not_bool_ref_pred(filled));
filled = true;
val = new_val;
cond.wake_one();
}
inline
void box<void>::put()
{
mutex::lock l(m);
cond.wait(l, not_bool_ref_pred(filled));
filled = true;
cond.wake_one();
}
template<typename T>
inline
bool box<T>::try_put(const T &new_val)
{
mutex::lock l(m);
if(!filled)
{
filled = true;
val = new_val;
cond.wake_one();
return true;
}
else
return false;
}
inline
bool box<void>::try_put()
{
mutex::lock l(m);
if(!filled)
{
filled = true;
cond.wake_one();
return true;
}
else
return false;
}
template<typename T>
inline
bool box<T>::timed_put(const T &new_val, const timespec &until)
{
mutex::lock l(m);
if(cond.timed_wait(l, until, not_bool_ref_pred(filled)))
{
filled = true;
val = new_val;
cond.wake_one();
return true;
}
else
return false;
}
inline
bool box<void>::timed_put(const timespec &until)
{
mutex::lock l(m);
if(cond.timed_wait(l, until, not_bool_ref_pred(filled)))
{
filled = true;
cond.wake_one();
return true;
}
else
return false;
}
template<typename T>
template<typename Mutator>
inline
void box<T>::update(const Mutator &m)
{
mutex::lock l(m);
cond.wait(l, bool_ref_pred(filled));
T new_val = m(val);
val = new_val;
cond.wake_one();
}
// A ptr_box is like a box, but it wraps a pointer to its internal
// object. When a filled ptr_box is destroyed, it deletes the
// pointer that it contains.
template<typename T>
class ptr_box
{
box<T *> b;
public:
ptr_box()
{
}
ptr_box(const T *val)
:b(val)
{
}
~ptr_box()
{
T *x;
if(b.try_get(x))
delete x;
}
T *take()
{
return b.take();
}
bool try_take(const T * &out)
{
return b.try_take(out);
}
bool timed_take(const T * &out, const timespec &until)
{
return b.timed_take(out);
}
void put(const T *in)
{
b.put(in);
}
bool try_put(const T *in)
{
return b.try_put(in);
}
bool timed_put(const T *in, const timespec &until)
{
return b.timed_put(in, until);
}
};
// A utility that proxies for noncopyable thread bootstrap
// objects. The only requirement is that the pointer passed
// to the constructor must not be destroyed until the thread
// completes.
template<typename F>
class bootstrap_proxy
{
F *f;
public:
bootstrap_proxy(F *_f)
: f(_f)
{
}
void operator()() const
{
(*f)();
}
};
template<typename F>
bootstrap_proxy<F> make_bootstrap_proxy(F *f)
{
return bootstrap_proxy<F>(f);
}
}
}
#endif // THREADS_H
|