/usr/include/ucommon/thread.h is in libucommon-dev 6.0.7-1.1.
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 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 | // Copyright (C) 2006-2010 David Sugar, Tycho Softworks.
//
// This file is part of GNU uCommon C++.
//
// GNU uCommon C++ is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU uCommon C++ 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with GNU uCommon C++. If not, see <http://www.gnu.org/licenses/>.
/**
* Thread classes and sychronization objects.
* The theory behind ucommon thread classes is that they would be used
* to create derived classes where thread-specific data can be stored as
* member data of the derived class. The run method is called when the
* context is executed. Since we use a pthread foundation, we support
* both detached threads and joinable threads. Objects based on detached
* threads should be created with new, and will automatically delete when
* the thread context exits. Joinable threads will be joined with deleted.
*
* The theory behind ucommon sychronization objects is that all upper level
* sychronization objects can be formed directly from a mutex and conditional.
* This includes semaphores, barriers, rwlock, our own specialized conditional
* lock, resource-bound locking, and recurive exclusive locks. Using only
* conditionals means we are not dependent on platform specific pthread
* implimentations that may not impliment some of these, and hence improves
* portability and consistency. Given that our rwlocks are recursive access
* locks, one can safely create read/write threading pairs where the read
* threads need not worry about deadlocks and the writers need not either if
* they only write-lock one instance at a time to change state.
* @file ucommon/thread.h
*/
/**
* An example of the thread queue class. This may be relevant to producer-
* consumer scenarios and realtime applications where queued messages are
* stored on a re-usable object pool.
* @example queue.cpp
*/
/**
* A simple example of threading and join operation.
* @example thread.cpp
*/
#ifndef _UCOMMON_THREAD_H_
#define _UCOMMON_THREAD_H_
#ifndef _UCOMMON_CPR_H_
#include <ucommon/cpr.h>
#endif
#ifndef _UCOMMON_ACCESS_H_
#include <ucommon/access.h>
#endif
#ifndef _UCOMMON_TIMERS_H_
#include <ucommon/timers.h>
#endif
#ifndef _UCOMMON_MEMORY_H_
#include <ucommon/memory.h>
#endif
NAMESPACE_UCOMMON
class SharedPointer;
/**
* The conditional is a common base for other thread synchronizing classes.
* Many of the complex sychronization objects, including barriers, semaphores,
* and various forms of read/write locks are all built from the conditional.
* This assures that the minimum functionality to build higher order thread
* synchronizing objects is a pure conditional, and removes dependencies on
* what may be optional features or functions that may have different
* behaviors on different pthread implimentations and platforms.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT Conditional
{
private:
friend class ConditionalAccess;
#if defined(_MSCONDITIONAL_)
CRITICAL_SECTION mutex;
CONDITION_VARIABLE cond;
#elif defined(_MSWINDOWS_)
enum {SIGNAL = 0, BROADCAST = 1};
HANDLE events[2];
unsigned waiting;
CRITICAL_SECTION mlock;
CRITICAL_SECTION mutex;
#else
#ifndef __PTH__
class __LOCAL attribute
{
public:
pthread_condattr_t attr;
attribute();
};
__LOCAL static attribute attr;
#endif
pthread_cond_t cond;
pthread_mutex_t mutex;
#endif
protected:
friend class TimedEvent;
/**
* Conditional wait for signal on millisecond timeout.
* @param timeout in milliseconds.
* @return true if signalled, false if timer expired.
*/
bool wait(timeout_t timeout);
/**
* Conditional wait for signal on timespec timeout.
* @param timeout as a high resolution timespec.
* @return true if signalled, false if timer expired.
*/
bool wait(struct timespec *timeout);
#ifdef _MSWINDOWS_
inline void lock(void)
{EnterCriticalSection(&mutex);};
inline void unlock(void)
{LeaveCriticalSection(&mutex);};
void wait(void);
void signal(void);
void broadcast(void);
#else
/**
* Lock the conditional's supporting mutex.
*/
inline void lock(void)
{pthread_mutex_lock(&mutex);};
/**
* Unlock the conditional's supporting mutex.
*/
inline void unlock(void)
{pthread_mutex_unlock(&mutex);};
/**
* Wait (block) until signalled.
*/
inline void wait(void)
{pthread_cond_wait(&cond, &mutex);};
/**
* Signal the conditional to release one waiting thread.
*/
inline void signal(void)
{pthread_cond_signal(&cond);};
/**
* Signal the conditional to release all waiting threads.
*/
inline void broadcast(void)
{pthread_cond_broadcast(&cond);};
#endif
/**
* Initialize and construct conditional.
*/
Conditional();
/**
* Destroy conditional, release any blocked threads.
*/
~Conditional();
public:
#if !defined(_MSWINDOWS_) && !defined(__PTH__)
/**
* Support function for getting conditional attributes for realtime
* scheduling.
* @return attributes to use for creating realtime conditionals.
*/
static inline pthread_condattr_t *initializer(void)
{return &attr.attr;};
#endif
/**
* Convert a millisecond timeout into use for high resolution
* conditional timers.
* @param hires timespec representation to set.
* @param timeout to convert.
*/
static void set(struct timespec *hires, timeout_t timeout);
};
/**
* The conditional rw seperates scheduling for optizming behavior or rw locks.
* This varient of conditonal seperates scheduling read (broadcast wakeup) and
* write (signal wakeup) based threads. This is used to form generic rwlock's
* as well as the specialized condlock.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT ConditionalAccess : private Conditional
{
protected:
#if defined _MSCONDITIONAL_
CONDITION_VARIABLE bcast;
#elif !defined(_MSWINDOWS_)
pthread_cond_t bcast;
#endif
unsigned pending, waiting, sharing;
/**
* Conditional wait for signal on millisecond timeout.
* @param timeout in milliseconds.
* @return true if signalled, false if timer expired.
*/
bool waitSignal(timeout_t timeout);
/**
* Conditional wait for broadcast on millisecond timeout.
* @param timeout in milliseconds.
* @return true if signalled, false if timer expired.
*/
bool waitBroadcast(timeout_t timeout);
/**
* Conditional wait for signal on timespec timeout.
* @param timeout as a high resolution timespec.
* @return true if signalled, false if timer expired.
*/
bool waitSignal(struct timespec *timeout);
/**
* Conditional wait for broadcast on timespec timeout.
* @param timeout as a high resolution timespec.
* @return true if signalled, false if timer expired.
*/
bool waitBroadcast(struct timespec *timeout);
/**
* Convert a millisecond timeout into use for high resolution
* conditional timers.
* @param hires timespec representation to set.
* @param timeout to convert.
*/
inline static void set(struct timespec *hires, timeout_t timeout)
{Conditional::set(hires, timeout);};
#ifdef _MSWINDOWS_
inline void lock(void)
{EnterCriticalSection(&mutex);};
inline void unlock(void)
{LeaveCriticalSection(&mutex);};
void waitSignal(void);
void waitBroadcast(void);
inline void signal(void)
{Conditional::signal();};
inline void broadcast(void)
{Conditional::broadcast();};
#else
/**
* Lock the conditional's supporting mutex.
*/
inline void lock(void)
{pthread_mutex_lock(&mutex);};
/**
* Unlock the conditional's supporting mutex.
*/
inline void unlock(void)
{pthread_mutex_unlock(&mutex);};
/**
* Wait (block) until signalled.
*/
inline void waitSignal(void)
{pthread_cond_wait(&cond, &mutex);};
/**
* Wait (block) until broadcast.
*/
inline void waitBroadcast(void)
{pthread_cond_wait(&bcast, &mutex);};
/**
* Signal the conditional to release one signalled thread.
*/
inline void signal(void)
{pthread_cond_signal(&cond);};
/**
* Signal the conditional to release all broadcast threads.
*/
inline void broadcast(void)
{pthread_cond_broadcast(&bcast);};
#endif
public:
/**
* Initialize and construct conditional.
*/
ConditionalAccess();
/**
* Destroy conditional, release any blocked threads.
*/
~ConditionalAccess();
/**
* Access mode shared thread scheduling.
*/
void access(void);
/**
* Exclusive mode write thread scheduling.
*/
void modify(void);
/**
* Release access mode read scheduling.
*/
void release(void);
/**
* Complete exclusive mode write scheduling.
*/
void commit(void);
/**
* Specify a maximum sharing (access) limit. This can be used
* to detect locking errors, such as when aquiring locks that are
* not released.
* @param max sharing level.
*/
void limit_sharing(unsigned max);
};
/**
* Event notification to manage scheduled realtime threads. The timer
* is advanced to sleep threads which then wakeup either when the timer
* has expired or they are notified through the signal handler. This can
* be used to schedule and signal one-time completion handlers or for time
* synchronized events signaled by an asychrononous I/O or event source.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT TimedEvent : public Timer
{
private:
#ifdef _MSWINDOWS_
HANDLE event;
#else
pthread_cond_t cond;
bool signalled;
#endif
pthread_mutex_t mutex;
protected:
/**
* Lock the object for wait or to manipulate derived data. This is
* relevant to manipulations in a derived class.
*/
void lock(void);
/**
* Release the object lock after waiting. This is relevent to
* manipulations in a derived class.
*/
void release(void);
/**
* Wait while locked. This can be used in more complex derived
* objects where we are concerned with synchronized access between
* the signaling and event thread. This can be used in place of
* wait, but lock and release methods must be used around it.
* @return true if time expired.
*/
bool sync(void);
public:
/**
* Create event handler and timer for timing of events.
*/
TimedEvent(void);
/**
* Create event handler and timer set to trigger a timeout.
* @param timeout in milliseconds.
*/
TimedEvent(timeout_t timeout);
/**
* Create event handler and timer set to trigger a timeout.
* @param timeout in seconds.
*/
TimedEvent(time_t timeout);
/**
* Destroy timer and release pending events.
*/
~TimedEvent();
/**
* Signal pending event. Object may be locked or unlocked. The
* signalling thread may choose to lock and check a condition in
* a derived class before signalling.
*/
void signal(void);
/**
* Wait to be signalled or until timer expires. This is a wrapper for
* expire for simple completion events.
* @param timeout to wait from last reset.
* @return true if signaled, false if timeout.
*/
bool wait(timeout_t timeout);
/**
* A simple wait until triggered.
*/
void wait(void);
/**
* Reset triggered conditional.
*/
void reset(void);
};
/**
* Portable recursive exclusive lock. This class is built from the
* conditional and hence does not require support for non-standard and
* platform specific extensions to pthread mutex to support recrusive
* style mutex locking. The exclusive protocol is implimented to support
* exclusive_lock referencing.
*/
class __EXPORT RecursiveMutex : private Conditional, public ExclusiveAccess
{
protected:
unsigned waiting;
unsigned lockers;
pthread_t locker;
virtual void _lock(void);
virtual void _unlock(void);
public:
/**
* Create rexlock.
*/
RecursiveMutex();
/**
* Acquire or increase locking.
*/
void lock(void);
/**
* Timed lock request.
*/
bool lock(timeout_t timeout);
/**
* Release or decrease locking.
*/
void release(void);
};
/**
* A generic and portable implimentation of Read/Write locking. This
* class impliments classical read/write locking, including "timed" locks.
* Support for scheduling threads to avoid writer starvation is also provided
* for. By building read/write locks from a conditional, we make them
* available on pthread implimetations and other platforms which do not
* normally include optional pthread rwlock's. We also do not restrict
* the number of threads that may use the lock. Finally, both the exclusive
* and shared protocols are implimented to support exclusive_lock and
* shared_lock referencing.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT ThreadLock : private ConditionalAccess, public ExclusiveAccess, public SharedAccess
{
protected:
unsigned writers;
pthread_t writeid;
virtual void _lock(void);
virtual void _share(void);
virtual void _unlock(void);
public:
/**
* Guard class to apply scope based access locking to objects. The rwlock
* is located from the rwlock pool rather than contained in the target
* object, and the read lock is released when the guard object falls out of
* scope. This is essentially an automation mechanism for mutex::reader.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT guard_reader
{
private:
const void *object;
public:
/**
* Create an unitialized instance of guard. Usually used with a
* guard = operator.
*/
guard_reader();
/**
* Construct a guard for a specific object.
* @param object to guard.
*/
guard_reader(const void *object);
/**
* Release mutex when guard falls out of scope.
*/
~guard_reader();
/**
* Set guard to mutex lock a new object. If a lock is currently
* held, it is released.
* @param object to guard.
*/
void set(const void *object);
/**
* Prematurely release a guard.
*/
void release(void);
/**
* Set guard to read lock a new object. If a lock is currently
* held, it is released.
* @param pointer to object to guard.
*/
inline void operator=(const void *pointer)
{set(pointer);};
};
/**
* Guard class to apply scope based exclusive locking to objects. The rwlock
* is located from the rwlock pool rather than contained in the target
* object, and the write lock is released when the guard object falls out of
* scope. This is essentially an automation mechanism for mutex::writer.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT guard_writer
{
private:
const void *object;
public:
/**
* Create an unitialized instance of guard. Usually used with a
* guard = operator.
*/
guard_writer();
/**
* Construct a guard for a specific object.
* @param object to guard.
*/
guard_writer(const void *object);
/**
* Release mutex when guard falls out of scope.
*/
~guard_writer();
/**
* Set guard to mutex lock a new object. If a lock is currently
* held, it is released.
* @param object to guard.
*/
void set(const void *object);
/**
* Prematurely release a guard.
*/
void release(void);
/**
* Set guard to read lock a new object. If a lock is currently
* held, it is released.
* @param pointer to object to guard.
*/
inline void operator=(const void *pointer)
{set(pointer);};
};
/**
* Create an instance of a rwlock.
*/
ThreadLock();
/**
* Request modify (write) access through the lock.
* @param timeout in milliseconds to wait for lock.
* @return true if locked, false if timeout.
*/
bool modify(timeout_t timeout = Timer::inf);
/**
* Request shared (read) access through the lock.
* @param timeout in milliseconds to wait for lock.
* @return true if locked, false if timeout.
*/
bool access(timeout_t timeout = Timer::inf);
/**
* Specify hash table size for guard protection. The default is 1.
* This should be called at initialization time from the main thread
* of the application before any other threads are created.
* @param size of hash table used for guarding.
*/
static void indexing(unsigned size);
/**
* Write protect access to an arbitrary object. This is like the
* protect function of mutex.
* @param object to protect.
* @param timeout in milliseconds to wait for lock.
* @return true if locked, false if timeout.
*/
static bool writer(const void *object, timeout_t timeout = Timer::inf);
/**
* Shared access to an arbitrary object. This is based on the protect
* function of mutex.
* @param object to share.
* @param timeout in milliseconds to wait for lock.
* @return true if shared, false if timeout.
*/
static bool reader(const void *object, timeout_t timeout = Timer::inf);
/**
* Release an arbitrary object that has been protected by a rwlock.
* @param object to release.
*/
static void release(const void *object);
/**
* Release the lock.
*/
void release(void);
};
/**
* Class for resource bound memory pools between threads. This is used to
* support a memory pool allocation scheme where a pool of reusable objects
* may be allocated, and the pool renewed by releasing objects or back.
* When the pool is used up, a pool consuming thread then must wait for
* a resource to be freed by another consumer (or timeout). This class is
* not meant to be used directly, but rather to build the synchronizing
* control between consumers which might be forced to wait for a resource.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT ReusableAllocator : protected Conditional
{
protected:
ReusableObject *freelist;
unsigned waiting;
/**
* Initialize reusable allocator through a conditional. Zero free list.
*/
ReusableAllocator();
/**
* Get next reusable object in the pool.
* @param object from list.
* @return next object.
*/
inline ReusableObject *next(ReusableObject *object)
{return object->getNext();};
/**
* Release resuable object
* @param object being released.
*/
void release(ReusableObject *object);
};
/**
* An optimized and convertable shared lock. This is a form of read/write
* lock that has been optimized, particularly for shared access. Support
* for scheduling access around writer starvation is also included. The
* other benefits over traditional read/write locks is that the code is
* a little lighter, and read (shared) locks can be converted to exclusive
* (write) locks to perform brief modify operations and then returned to read
* locks, rather than having to release and re-aquire locks to change mode.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT ConditionalLock : protected ConditionalAccess, public SharedAccess
{
protected:
class Context : public LinkedObject
{
public:
inline Context(LinkedObject **root) : LinkedObject(root) {};
pthread_t thread;
unsigned count;
};
LinkedObject *contexts;
virtual void _share(void);
virtual void _unlock(void);
Context *getContext(void);
public:
/**
* Construct conditional lock for default concurrency.
*/
ConditionalLock();
/**
* Destroy conditional lock.
*/
~ConditionalLock();
/**
* Acquire write (exclusive modify) lock.
*/
void modify(void);
/**
* Commit changes / release a modify lock.
*/
void commit(void);
/**
* Acquire access (shared read) lock.
*/
void access(void);
/**
* Release a shared lock.
*/
void release(void);
/**
* Convert read lock into exclusive (write/modify) access. Schedule
* when other readers sharing.
*/
virtual void exclusive(void);
/**
* Return an exclusive access lock back to share mode.
*/
virtual void share(void);
};
/**
* A portable implimentation of "barrier" thread sychronization. A barrier
* waits until a specified number of threads have all reached the barrier,
* and then releases all the threads together. This implimentation works
* regardless of whether the thread library supports barriers since it is
* built from conditional. It also differs in that the number of threads
* required can be changed dynamically at runtime, unlike pthread barriers
* which, when supported, have a fixed limit defined at creation time. Since
* we use conditionals, another feature we can add is optional support for a
* wait with timeout.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT barrier : private Conditional
{
private:
unsigned count;
unsigned waits;
public:
/**
* Construct a barrier with an initial size.
* @param count of threads required.
*/
barrier(unsigned count);
/**
* Destroy barrier and release pending threads.
*/
~barrier();
/**
* Dynamically alter the number of threads required. If the size is
* set below the currently waiting threads, then the barrier releases.
* @param count of threads required.
*/
void set(unsigned count);
/**
* Dynamically increment the number of threads required.
*/
void inc(void);
/**
* Reduce the number of threads required.
*/
void dec(void);
/**
* Alternative prefix form of the same increment operation.
* @return the current amount of threads.
*/
unsigned operator++(void);
unsigned operator--(void);
/**
* Wait at the barrier until the count of threads waiting is reached.
*/
void wait(void);
/**
* Wait at the barrier until either the count of threads waiting is
* reached or a timeout has occurred.
* @param timeout to wait in milliseconds.
* @return true if barrier reached, false if timer expired.
*/
bool wait(timeout_t timeout);
};
/**
* A portable counting semaphore class. A semaphore will allow threads
* to pass through it until the count is reached, and blocks further threads.
* Unlike pthread semaphore, our semaphore class supports it's count limit
* to be altered during runtime and the use of timed waits. This class also
* implements the shared_lock protocol.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT Semaphore : public SharedAccess, protected Conditional
{
protected:
unsigned count, waits, used;
virtual void _share(void);
virtual void _unlock(void);
public:
/**
* Construct a semaphore with an initial count of threads to permit.
*/
Semaphore(unsigned count = 0);
/**
* Wait until the semphore usage count is less than the thread limit.
* Increase used count for our thread when unblocked.
*/
void wait(void);
/**
* Wait until the semphore usage count is less than the thread limit.
* Increase used count for our thread when unblocked, or return without
* changing if timed out.
* @param timeout to wait in millseconds.
* @return true if success, false if timeout.
*/
bool wait(timeout_t timeout);
/**
* Alter semaphore limit at runtime
* @param count of threads to allow.
*/
void set(unsigned count);
/**
* Release the semaphore after waiting for it.
*/
void release(void);
/**
* Convenience operator to wait on a counting semaphore.
*/
inline void operator++(void)
{wait();};
/**
* Convenience operator to release a counting semaphore.
*/
inline void operator--(void)
{release();};
};
/**
* Generic non-recursive exclusive lock class. This class also impliments
* the exclusive_lock protocol. In addition, an interface is offered to
* support dynamically managed mutexes which are internally pooled. These
* can be used to protect and serialize arbitrary access to memory and
* objects on demand. This offers an advantage over embedding mutexes to
* serialize access to individual objects since the maximum number of
* mutexes will never be greater than the number of actually running threads
* rather than the number of objects being potentially protected. The
* ability to hash the pointer address into an indexed table further optimizes
* access by reducing the chance for collisions on the primary index mutex.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT Mutex : public ExclusiveAccess
{
protected:
pthread_mutex_t mlock;
virtual void _lock(void);
virtual void _unlock(void);
public:
/**
* Guard class to apply scope based mutex locking to objects. The mutex
* is located from the mutex pool rather than contained in the target
* object, and the lock is released when the guard object falls out of
* scope. This is essentially an automation mechanism for mutex::protect.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT guard
{
private:
const void *object;
public:
/**
* Create an unitialized instance of guard. Usually used with a
* guard = operator.
*/
guard();
/**
* Construct a guard for a specific object.
* @param object to guard.
*/
guard(const void *object);
/**
* Release mutex when guard falls out of scope.
*/
~guard();
/**
* Set guard to mutex lock a new object. If a lock is currently
* held, it is released.
* @param object to guard.
*/
void set(const void *object);
/**
* Prematurely release a guard.
*/
void release(void);
/**
* Set guard to mutex lock a new object. If a lock is currently
* held, it is released.
* @param pointer to object to guard.
*/
inline void operator=(void *pointer)
{set(pointer);};
};
/**
* Create a mutex lock.
*/
Mutex();
/**
* Destroy mutex lock, release waiting threads.
*/
~Mutex();
/**
* Acquire mutex lock. This is a blocking operation.
*/
inline void acquire(void)
{pthread_mutex_lock(&mlock);};
/**
* Acquire mutex lock. This is a blocking operation.
*/
inline void lock(void)
{pthread_mutex_lock(&mlock);};
/**
* Release acquired lock.
*/
inline void unlock(void)
{pthread_mutex_unlock(&mlock);};
/**
* Release acquired lock.
*/
inline void release(void)
{pthread_mutex_unlock(&mlock);};
/**
* Convenience function to acquire os native mutex lock directly.
* @param lock to acquire.
*/
inline static void acquire(pthread_mutex_t *lock)
{pthread_mutex_lock(lock);};
/**
* Convenience function to release os native mutex lock directly.
* @param lock to release.
*/
inline static void release(pthread_mutex_t *lock)
{pthread_mutex_unlock(lock);};
/**
* Specify hash table size for guard protection. The default is 1.
* This should be called at initialization time from the main thread
* of the application before any other threads are created.
* @param size of hash table used for guarding.
*/
static void indexing(unsigned size);
/**
* Specify pointer/object/resource to guard protect. This uses a
* dynamically managed mutex.
* @param pointer to protect.
*/
static void protect(const void *pointer);
/**
* Specify a pointer/object/resource to release.
* @param pointer to release.
*/
static void release(const void *pointer);
};
/**
* A mutex locked object smart pointer helper class. This is particularly
* useful in referencing objects which will be protected by the mutex
* protect function. When the pointer falls out of scope, the protecting
* mutex is also released. This is meant to be used by the typed
* mutex_pointer template.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT auto_protect
{
private:
// cannot copy...
inline auto_protect(const auto_object &pointer) {};
protected:
const void *object;
auto_protect();
public:
/**
* Construct a protected pointer referencing an existing object.
* @param object we point to.
*/
auto_protect(const void *object);
/**
* Delete protected pointer. When it falls out of scope the associated
* mutex is released.
*/
~auto_protect();
/**
* Manually release the pointer. This releases the mutex.
*/
void release(void);
/**
* Test if the pointer is not set.
* @return true if the pointer is not referencing anything.
*/
inline bool operator!() const
{return object == NULL;};
/**
* Test if the pointer is referencing an object.
* @return true if the pointer is currently referencing an object.
*/
inline operator bool() const
{return object != NULL;};
/**
* Set our pointer to a specific object. If the pointer currently
* references another object, the associated mutex is released. The
* pointer references our new object and that new object is locked.
* @param object to assign to.
*/
void operator=(const void *object);
};
/**
* An object pointer that uses mutex to assure thread-safe singleton use.
* This class is used to support a threadsafe replacable pointer to a object.
* This class is used to form and support the templated locked_pointer class
* and used with the locked_release class. An example of where this might be
* used is in config file parsers, where a seperate thread may process and
* generate a new config object for new threads to refernce, while the old
* configuration continues to be used by a reference counted instance that
* goes away when it falls out of scope.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT LockedPointer
{
private:
friend class locked_release;
pthread_mutex_t mutex;
ObjectProtocol *pointer;
protected:
/**
* Create an instance of a locked pointer.
*/
LockedPointer();
/**
* Replace existing object with a new one for next request.
* @param object to register with pointer.
*/
void replace(ObjectProtocol *object);
/**
* Create a duplicate reference counted instance of the current object.
* @return duplicate reference counted object.
*/
ObjectProtocol *dup(void);
/**
* Replace existing object through assignment.
* @param object to assign.
*/
inline void operator=(ObjectProtocol *object)
{replace(object);};
};
/**
* Shared singleton object. A shared singleton object is a special kind of
* object that may be shared by multiple threads but which only one active
* instance is allowed to exist. The shared object is managed by the
* templated shared pointer class, and is meant to be inherited as a base
* class for the derived shared singleton type.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT SharedObject
{
protected:
friend class SharedPointer;
/**
* Commit is called when a shared singleton is accepted and replaces
* a prior instance managed by a shared pointer. Commit occurs
* when replace is called on the shared pointer, and is assured to
* happen only when no threads are accessing either the current
* or the prior instance that was previously protected by the pointer.
* @param pointer that now holds the object.
*/
virtual void commit(SharedPointer *pointer);
public:
/**
* Allows inherited virtual.
*/
virtual ~SharedObject();
};
/**
* The shared pointer is used to manage a singleton instance of shared object.
* This class is used to support the templated shared_pointer class and the
* shared_release class, and is not meant to be used directly or as a base
* for anything else. One or more threads may aquire a shared lock to the
* singleton object through this pointer, and it can only be replaced with a
* new singleton instance when no threads reference it. The conditional lock
* is used to manage shared access for use and exclusive access when modified.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT SharedPointer : protected ConditionalAccess
{
private:
friend class shared_release;
SharedObject *pointer;
protected:
/**
* Created shared locking for pointer. Must be assigned by replace.
*/
SharedPointer();
/**
* Destroy lock and release any blocked threads.
*/
~SharedPointer();
/**
* Replace existing singleton instance with new one. This happens
* during exclusive locking, and the commit method of the object
* will be called.
* @param object being set.
*/
void replace(SharedObject *object);
/**
* Acquire a shared reference to the singleton object. This is a
* form of shared access lock. Derived classes and templates access
* "release" when the shared pointer is no longer needed.
* @return shared object.
*/
SharedObject *share(void);
};
/**
* An abstract class for defining classes that operate as a thread. A derived
* thread class has a run method that is invoked with the newly created
* thread context, and can use the derived object to store all member data
* that needs to be associated with that context. This means the derived
* object can safely hold thread-specific data that is managed with the life
* of the object, rather than having to use the clumsy thread-specific data
* management and access functions found in thread support libraries.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT Thread
{
protected:
// may be used in future if we need cancelable threads...
#ifdef _MSWINDOWS_
HANDLE cancellor;
#else
void *cancellor;
#endif
enum {} reserved; // cancel mode?
pthread_t tid;
size_t stack;
int priority;
/**
* Create a thread object that will have a preset stack size. If 0
* is used, then the stack size is os defined/default.
* @param stack size to use or 0 for default.
*/
Thread(size_t stack = 0);
/**
* Map thread for get method. This should be called from start of the
* run() method of a derived class.
*/
void map(void);
/**
* Check if running.
*/
virtual bool is_active(void);
public:
/**
* Set thread priority without disrupting scheduling if possible.
* Based on scheduling policy. It is recommended that the process
* is set for realtime scheduling, and this method is actually for
* internal use.
*/
void setPriority(void);
/**
* Yield execution context of the current thread. This is a static
* and may be used anywhere.
*/
static void yield(void);
/**
* Sleep current thread for a specified time period.
* @param timeout to sleep for in milliseconds.
*/
static void sleep(timeout_t timeout);
/**
* Get mapped thread object. This returns the mapped base class of the
* thread object of the current executing context. You will need to
* cast to the correct derived class to access derived thread-specific
* storage. If the current thread context is not mapped NULL is returned.
*/
static Thread *get(void);
/**
* Abstract interface for thread context run method.
*/
virtual void run(void) = 0;
/**
* Destroy thread object, thread-specific data, and execution context.
*/
virtual ~Thread();
/**
* Exit the thread context. This function should NO LONGER be called
* directly to exit a running thread. Instead this method will only be
* used to modify the behavior of the thread context at thread exit,
* including detached threads which by default delete themselves. This
* documented usage was changed to support Mozilla NSPR exit behavior
* in case we support NSPR as an alternate thread runtime in the future.
*/
virtual void exit(void);
/**
* Used to initialize threading library. May be needed for some platforms.
*/
static void init(void);
/**
* Used to specify scheduling policy for threads above priority "0".
* Normally we apply static realtime policy SCHED_FIFO (default) or
* SCHED_RR. However, we could apply SCHED_OTHER, etc.
*/
static void policy(int polid);
/**
* Set concurrency level of process. This is essentially a portable
* wrapper for pthread_setconcurrency.
*/
static void concurrency(int level);
/**
* Determine if two thread identifiers refer to the same thread.
* @param thread1 to test.
* @param thread2 to test.
* @return true if both are the same context.
*/
static bool equal(pthread_t thread1, pthread_t thread2);
/**
* Get current thread id.
* @return thread id.
*/
static pthread_t self(void);
inline operator bool()
{return is_active();}
inline bool operator!()
{return !is_active();}
inline bool isRunning(void)
{return is_active();}
};
/**
* A child thread object that may be joined by parent. A child thread is
* a type of thread in which the parent thread (or process main thread) can
* then wait for the child thread to complete and then delete the child object.
* The parent thread can wait for the child thread to complete either by
* calling join, or performing a "delete" of the derived child object. In
* either case the parent thread will suspend execution until the child thread
* exits.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT JoinableThread : public Thread
{
protected:
#ifdef _MSWINDOWS_
HANDLE running;
#else
volatile bool running;
#endif
volatile bool joining;
/**
* Create a joinable thread with a known context stack size.
* @param size of stack for thread context or 0 for default.
*/
JoinableThread(size_t size = 0);
/**
* Delete child thread. Parent thread suspends until child thread
* run method completes or child thread calls it's exit method.
*/
virtual ~JoinableThread();
/**
* Join thread with parent. Calling from a child thread to exit is
* now depreciated behavior and in the future will not be supported.
* Threads should always return through their run() method.
*/
void join(void);
bool is_active(void);
virtual void run(void) = 0;
public:
/**
* Start execution of child context. This must be called after the
* child object is created (perhaps with "new") and before it can be
* joined. This method actually begins the new thread context, which
* then calls the object's run method. Optionally raise the priority
* of the thread when it starts under realtime priority.
* @param priority of child thread.
*/
void start(int priority = 0);
/**
* Start execution of child context as background thread. This is
* assumed to be off main thread, with a priority lowered by one.
*/
inline void background(void)
{start(-1);};
};
/**
* A detached thread object that is stand-alone. This object has no
* relationship with any other running thread instance will be automatically
* deleted when the running thread instance exits, either by it's run method
* exiting, or explicity calling the exit member function.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT DetachedThread : public Thread
{
protected:
bool active;
/**
* Create a detached thread with a known context stack size.
* @param size of stack for thread context or 0 for default.
*/
DetachedThread(size_t size = 0);
/**
* Destroys object when thread context exits. Never externally
* deleted. Derived object may also have destructor to clean up
* thread-specific member data.
*/
~DetachedThread();
/**
* Exit context of detached thread. Thread object will be deleted.
* This function should NO LONGER be called directly to exit a running
* thread. Instead, the thread should only "return" through the run()
* method to exit. The documented usage was changed so that exit() can
* still be used to modify the "delete this" behavior of detached threads
* while merging thread exit behavior with Mozilla NSPR.
*/
void exit(void);
bool is_active(void);
virtual void run(void) = 0;
public:
/**
* Start execution of detached context. This must be called after the
* object is created (perhaps with "new"). This method actually begins
* the new thread context, which then calls the object's run method.
* @param priority to start thread with.
*/
void start(int priority = 0);
};
/**
* Auto-pointer support class for locked objects. This is used as a base
* class for the templated locked_instance class that uses the managed
* LockedPointer to assign a reference to an object. When the locked
* instance falls out of scope, the object is derefenced. Ideally the
* pointer typed object should be based on the reference counted object class.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT locked_release
{
protected:
ObjectProtocol *object; /**< locked object protected by locked_release */
/**
* Create an unassigned locked object pointer base.
*/
locked_release();
/**
* Construct a locked object instance base from an existing instance. This
* will create a duplicate (retained) reference.
* @param object to copy from.
*/
locked_release(const locked_release &object);
public:
/**
* Construct a locked object instance base from a LockedPointer. References
* a retained instance of the underlying object from the LockedPointer.
* @param pointer of locked pointer to assign from.
*/
locked_release(LockedPointer &pointer);
/**
* Auto-release pointer to locked object instance. This is used to release
* a reference when the pointer template falls out of scope.
*/
~locked_release();
/**
* Manually release the object reference.
*/
void release(void);
/**
* Assign a locked object pointer. If an existing object is already
* assigned, the existing pointer is released.
* @param pointer reference through locked object.
*/
locked_release &operator=(LockedPointer &pointer);
};
/**
* Auto-pointer support class for shared singleton objects. This is used as
* a base class for the templated shared_instance class that uses shared
* access locking through the SharedPointer class. When the shared instance
* falls out of scope, the SharedPointer lock is released. The pointer
* typed object must be based on the SharedObject class.
* @author David Sugar <dyfet@gnutelephony.org>
*/
class __EXPORT shared_release
{
protected:
SharedPointer *ptr; /**< Shared lock for protected singleton */
/**
* Create an unassigned shared singleton object pointer base.
*/
shared_release();
/**
* Construct a shared object instance base from an existing instance. This
* will assign an additional shared lock.
* @param object to copy from.
*/
shared_release(const shared_release &object);
public:
/**
* Access lock a shared singleton instance from a SharedPointer.
* @param pointer of shared pointer to assign from.
*/
shared_release(SharedPointer &pointer);
/**
* Auto-unlock shared lock for singleton instance protected by shared
* pointer. This is used to unlock when the instance template falls out
* of scope.
*/
~shared_release();
/**
* Manually release access to shared singleton object.
*/
void release(void);
/**
* Get pointer to singleton object that we have shared lock for.
* @return shared object singleton.
*/
SharedObject *get(void);
/**
* Assign shared lock access to shared singleton. If an existing
* shared lock is held for another pointer, it is released.
* @param pointer access for shared object.
*/
shared_release &operator=(SharedPointer &pointer);
};
/**
* Templated shared pointer for singleton shared objects of specific type.
* This is used as typed template for the SharedPointer object reference
* management class. This is used to supply a typed singleton shared
* instance to the typed shared_instance template class.
* @author David Sugar <dyfet@gnutelephony.org>
*/
template<class T>
class shared_pointer : public SharedPointer
{
public:
/**
* Created shared locking for typed singleton pointer.
*/
inline shared_pointer() : SharedPointer() {};
/**
* Acquire a shared (duplocate) reference to the typed singleton object.
* This is a form of shared access lock. Derived classes and templates
* access conditionallock "release" when the shared pointer is no longer
* needed.
* @return typed shared object.
*/
inline const T *dup(void)
{return static_cast<const T*>(SharedPointer::share());};
/**
* Replace existing typed singleton instance with new one. This happens
* during exclusive locking, and the commit method of the typed object
* will be called.
* @param object being set.
*/
inline void replace(T *object)
{SharedPointer::replace(object);};
/**
* Replace existing typed singleton object through assignment.
* @param object to assign.
*/
inline void operator=(T *object)
{replace(object);};
/**
* Access shared lock typed singleton object by pointer reference.
* @return typed shared object.
*/
inline T *operator*()
{return dup();};
};
/**
* Templated locked pointer for referencing locked objects of specific type.
* This is used as typed template for the LockedPointer object reference
* management class. This is used to supply a typed locked instances
* to the typed locked_instance template class.
* @author David Sugar <dyfet@gnutelephony.org>
*/
template<class T>
class locked_pointer : public LockedPointer
{
public:
/**
* Create an instance of a typed locked pointer.
*/
inline locked_pointer() : LockedPointer() {};
/**
* Create a duplicate reference counted instance of the current typed
* object.
* @return duplicate reference counted typed object.
*/
inline T* dup(void)
{return static_cast<T *>(LockedPointer::dup());};
/**
* Replace existing typed object with a new one for next request.
* @param object to register with pointer.
*/
inline void replace(T *object)
{LockedPointer::replace(object);};
/**
* Replace existing object through assignment.
* @param object to assign.
*/
inline void operator=(T *object)
{replace(object);};
/**
* Create a duplicate reference counted instance of the current typed
* object by pointer reference.
* @return duplicate reference counted typed object.
*/
inline T *operator*()
{return dup();};
};
/**
* A templated smart pointer instance for lock protected objects.
* This is used to reference an instance of a typed locked_pointer.
* @author David Sugar <dyfet@gnutelephony.org>
*/
template<class T>
class locked_instance : public locked_release
{
public:
/**
* Construct empty locked instance of typed object.
*/
inline locked_instance() : locked_release() {};
/**
* Construct locked instance of typed object from matching locked_pointer.
* @param pointer to get instance from.
*/
inline locked_instance(locked_pointer<T> &pointer) : locked_release(pointer) {};
/**
* Extract instance of locked typed object by pointer reference.
* @return instance of typed object.
*/
inline T& operator*() const
{return *(static_cast<T&>(object));};
/**
* Access member of instance of locked typed object by member reference.
* @return instance of typed object.
*/
inline T* operator->() const
{return static_cast<T*>(object);};
/**
* Get pointer to instance of locked typed object.
* @return instance of typed object.
*/
inline T* get(void) const
{return static_cast<T*>(object);};
};
/**
* A templated smart pointer instance for shared singleton typed objects.
* This is used to access the shared lock instance of the singleton.
* @author David Sugar <dyfet@gnutelephony.org>
*/
template<class T>
class shared_instance : public shared_release
{
public:
/**
* Construct empty instance to reference shared typed singleton.
*/
inline shared_instance() : shared_release() {};
/**
* Construct shared access instance of shared typed singleton from matching
* shared_pointer.
* @param pointer to get instance from.
*/
inline shared_instance(shared_pointer<T> &pointer) : shared_release(pointer) {};
/**
* Access shared typed singleton object this instance locks and references.
*/
inline const T& operator*() const
{return *(static_cast<const T&>(ptr->pointer));};
/**
* Access member of shared typed singleton object this instance locks and
* references.
*/
inline const T* operator->() const
{return static_cast<const T*>(ptr->pointer);};
/**
* Access pointer to typed singleton object this instance locks and
* references.
*/
inline const T* get(void) const
{return static_cast<const T*>(ptr->pointer);};
};
/**
* Typed smart locked pointer class. This is used to manage references to
* objects which are protected by an auto-generated mutex. The mutex is
* released when the pointer falls out of scope.
* @author David Sugar <dyfet@gnutelephony.org>
*/
template <class T>
class mutex_pointer : public auto_protect
{
public:
/**
* Create a pointer with no reference.
*/
inline mutex_pointer() : auto_protect() {};
/**
* Create a pointer with a reference to a heap object.
* @param object we are referencing.
*/
inline mutex_pointer(T* object) : auto_protect(object) {};
/**
* Reference object we are pointing to through pointer indirection.
* @return object we are pointing to.
*/
inline T& operator*() const
{return *(static_cast<T&>(auto_protect::object));};
/**
* Reference member of object we are pointing to.
* @return reference to member of pointed object.
*/
inline T* operator->() const
{return static_cast<T*>(auto_protect::object);};
/**
* Get pointer to object.
* @return pointer or NULL if we are not referencing an object.
*/
inline T* get(void) const
{return static_cast<T*>(auto_protect::object);};
};
/**
* Convenience function to start a joinable thread.
* @param thread to start.
* @param priority of thread.
*/
inline void start(JoinableThread *thread, int priority = 0)
{thread->start(priority);}
/**
* Convenience function to start a detached thread.
* @param thread to start.
* @param priority of thread.
*/
inline void start(DetachedThread *thread, int priority = 0)
{thread->start(priority);}
/**
* Convenience type for using conditional locks.
*/
typedef ConditionalLock condlock_t;
/**
* Convenience type for scheduling access.
*/
typedef ConditionalAccess accesslock_t;
/**
* Convenience type for using timed events.
*/
typedef TimedEvent timedevent_t;
/**
* Convenience type for using exclusive mutex locks.
*/
typedef Mutex mutex_t;
/**
* Convenience type for using read/write locks.
*/
typedef ThreadLock rwlock_t;
/**
* Convenience type for using recursive exclusive locks.
*/
typedef RecursiveMutex rexlock_t;
/**
* Convenience type for using counting semaphores.
*/
typedef Semaphore semaphore_t;
/**
* Convenience type for using thread barriers.
*/
typedef barrier barrier_t;
/**
* Convenience function to wait on a barrier.
* @param barrier to wait.
*/
inline void wait(barrier_t &barrier)
{barrier.wait();}
/**
* Convenience function to wait on a semaphore.
* @param semaphore to wait on.
* @param timeout to wait for.
*/
inline void wait(semaphore_t &semaphore, timeout_t timeout = Timer::inf)
{semaphore.wait(timeout);}
/**
* Convenience function to release a semaphore.
* @param semaphore to release.
*/
inline void release(semaphore_t &semaphore)
{semaphore.release();}
/**
* Convenience function to acquire a mutex.
* @param mutex to acquire.
*/
inline void acquire(mutex_t &mutex)
{mutex.lock();}
/**
* Convenience function to release a mutex.
* @param mutex to release.
*/
inline void release(mutex_t &mutex)
{mutex.release();}
/**
* Convenience function to exclusively schedule conditional access.
* @param lock to make exclusive.
*/
inline void modify(accesslock_t &lock)
{lock.modify();}
/**
* Convenience function to shared read schedule conditional access.
* @param lock to access shared.
*/
inline void access(accesslock_t &lock)
{lock.access();}
/**
* Convenience function to release an access lock.
* @param lock to release.
*/
inline void release(accesslock_t &lock)
{lock.release();}
/**
* Convenience function to commit an exclusive access lock.
* lock.
* @param lock to commit.
*/
inline void commit(accesslock_t &lock)
{lock.commit();}
/**
* Convenience function to exclusively lock shared conditional lock.
* @param lock to make exclusive.
*/
inline void exclusive(condlock_t &lock)
{lock.exclusive();}
/**
* Convenience function to restore shared access on a conditional lock.
* @param lock to make shared.
*/
inline void share(condlock_t &lock)
{lock.share();}
/**
* Convenience function to exclusively aquire a conditional lock.
* @param lock to acquire for modify.
*/
inline void modify(condlock_t &lock)
{lock.modify();}
/**
* Convenience function to commit and release an exclusively locked conditional
* lock.
* @param lock to commit.
*/
inline void commit(condlock_t &lock)
{lock.commit();}
/**
* Convenience function for shared access to a conditional lock.
* @param lock to access.
*/
inline void access(condlock_t &lock)
{lock.access();}
/**
* Convenience function to release shared access to a conditional lock.
* @param lock to release.
*/
inline void release(condlock_t &lock)
{lock.release();}
/**
* Convenience function for exclusive write access to a read/write lock.
* @param lock to write lock.
* @param timeout to wait for exclusive locking.
*/
inline bool exclusive(rwlock_t &lock, timeout_t timeout = Timer::inf)
{return lock.modify(timeout);}
/**
* Convenience function for shared read access to a read/write lock.
* @param lock to share read lock.
* @param timeout to wait for shared access.
*/
inline bool share(rwlock_t &lock, timeout_t timeout = Timer::inf)
{return lock.access(timeout);}
/**
* Convenience function to release a shared lock.
* @param lock to release.
*/
inline void release(rwlock_t &lock)
{lock.release();}
/**
* Convenience function to lock a shared recursive mutex lock.
* @param lock to acquire.
*/
inline void lock(rexlock_t &lock)
{lock.lock();}
/**
* Convenience function to release a shared recursive mutex lock.
* @param lock to release.
*/
inline void release(rexlock_t &lock)
{lock.release();}
inline bool _sync_protect_(const void *obj)
{
Mutex::protect(obj);
return true;
}
inline bool _sync_release_(const void *obj)
{
Mutex::release(obj);
return false;
}
inline bool _rw_reader_(const void *obj)
{
ThreadLock::reader(obj);
return true;
}
inline bool _rw_writer_(const void *obj)
{
ThreadLock::writer(obj);
return true;
}
inline bool _rw_release_(const void *obj)
{
ThreadLock::release(obj);
return false;
}
#define ENTER_EXCLUSIVE \
do { static pthread_mutex_t __sync__ = PTHREAD_MUTEX_INITIALIZER; \
pthread_mutex_lock(&__sync__);
#define LEAVE_EXCLUSIVE \
pthread_mutex_unlock(&__sync__);} while(0);
#define SYNC(obj) for(bool _sync_flag_ = _sync_protect_(obj); _sync_flag_; _sync_flag_ = _sync_release_(obj))
#define SHARED(obj) for(bool _sync_flag_ = _rw_reader_(obj); _sync_flag_; _sync_flag_ = _rw_release_(obj))
#define EXCLUSIVE(obj) for(bool _sync_flag_ = _rw_writer_(obj); _sync_flag_; _sync_flag_ = _rw_release_(obj))
END_NAMESPACE
#endif
|