2
0
mirror of https://github.com/boostorg/thread.git synced 2026-02-03 09:42:16 +00:00

Compare commits

..

40 Commits

Author SHA1 Message Date
William E. Kempf
9b8c62d45a Merged from RC_1_29_0
[SVN r16126]
2002-11-05 22:43:42 +00:00
nobody
7d438e9f25 This commit was manufactured by cvs2svn to create branch
'thread_development'.

[SVN r16006]
2002-10-28 14:10:15 +00:00
John D. Moore
d525388fb2 Simple tests for shared memory objects. Need multiple process tests as well.
[SVN r14428]
2002-07-12 19:33:02 +00:00
John D. Moore
1029d0d2bb Implementations for win32 + POSIX. Win32 tested.
[SVN r14427]
2002-07-12 19:30:30 +00:00
John D. Moore
00038f78e5 Moved to lower level class
[SVN r14426]
2002-07-12 19:25:32 +00:00
William E. Kempf
2dc67ea9ad Removed lock from get/set in TSS.
[SVN r14356]
2002-07-08 21:08:51 +00:00
William E. Kempf
602faacb35 Changes to tss for proper ordering of destructors
[SVN r14354]
2002-07-08 17:37:39 +00:00
William E. Kempf
0f078f33cb POSIX bug fixes.
[SVN r14316]
2002-07-05 17:52:56 +00:00
William E. Kempf
cf77472dfe POSIX bug fixes.
[SVN r14315]
2002-07-05 17:50:20 +00:00
William E. Kempf
8cc40e5e07 POSIX bug fixes.
[SVN r14314]
2002-07-05 17:45:13 +00:00
William E. Kempf
28d675b4c9 POSIX bug fixes.
[SVN r14313]
2002-07-05 17:38:43 +00:00
William E. Kempf
27b2b14c17 Added generation tracking to tss.
[SVN r14312]
2002-07-05 17:30:36 +00:00
William E. Kempf
cc5dd8a978 Fixed order of thread exit routines.
[SVN r14294]
2002-07-03 18:06:30 +00:00
William E. Kempf
81ee94ce3c Modified TSS to use defined destruction ordering.
[SVN r14291]
2002-07-03 15:54:10 +00:00
William E. Kempf
184e604287 'Fixed' tss bug.
[SVN r14252]
2002-06-27 22:18:05 +00:00
William E. Kempf
50dccc1f66 Removed CS and most 'process_detach' stuff from threadmon
[SVN r14250]
2002-06-27 19:40:41 +00:00
John D. Moore
30b766a02e Initial version for discussion
[SVN r14236]
2002-06-25 12:35:44 +00:00
William E. Kempf
48e8588af0 First go at refactoring tss and next version of thread class.
[SVN r14221]
2002-06-21 18:33:59 +00:00
William E. Kempf
a40b3657f6 Fixed pthread_detach bug
[SVN r13989]
2002-05-20 16:33:01 +00:00
William E. Kempf
1000f77180 Refactored thread
[SVN r13988]
2002-05-20 16:26:57 +00:00
William E. Kempf
518c5c8215 Added thread_group tests
[SVN r13952]
2002-05-16 14:34:03 +00:00
William E. Kempf
d30279342a Flushed output
[SVN r13943]
2002-05-15 22:40:00 +00:00
William E. Kempf
4c9ca0edae Fixed member initialization order warnings
[SVN r13942]
2002-05-15 22:36:35 +00:00
William E. Kempf
c163f90071 Added missing typename keywords
[SVN r13941]
2002-05-15 22:34:16 +00:00
William E. Kempf
1404d8558b Removed id parameters from thread_pool tests
[SVN r13940]
2002-05-15 22:32:38 +00:00
William E. Kempf
c8762d5c91 Removed id parameters from thread_pool tests
[SVN r13939]
2002-05-15 22:27:48 +00:00
William E. Kempf
11d3f9feb4 Changed <limits> to <boost/limits.hpp>
[SVN r13938]
2002-05-15 22:16:30 +00:00
William E. Kempf
3130149dfd Fixed bugs in rw_mutex.cpp caused by missing typename keywords
[SVN r13937]
2002-05-15 22:13:20 +00:00
William E. Kempf
4808ccb316 Refactoring tests
[SVN r13936]
2002-05-15 22:01:36 +00:00
William E. Kempf
7ae3687ed8 Bug fixes for rw_mutex and refactoring of tests
[SVN r13925]
2002-05-15 17:46:53 +00:00
William E. Kempf
bb5f17bf04 Bug fixes for rw_mutex and refactoring of tests
[SVN r13924]
2002-05-15 17:43:01 +00:00
William E. Kempf
a32df1aad9 Merged trunk changes
[SVN r13911]
2002-05-15 15:27:18 +00:00
William E. Kempf
da86b991e5 Updated thread_pool.html
[SVN r13907]
2002-05-15 14:54:18 +00:00
William E. Kempf
d12508b97f Refactored thread_pool implementation
[SVN r13627]
2002-05-02 21:42:22 +00:00
William E. Kempf
98af8c50c4 Updated documentation for barrier
[SVN r13598]
2002-04-30 21:46:53 +00:00
William E. Kempf
7bb5c1b4e2 Modified barrier implementation
[SVN r13597]
2002-04-30 21:27:21 +00:00
William E. Kempf
07ecf15f4c Added rw_mutex
[SVN r13593]
2002-04-30 19:10:14 +00:00
William E. Kempf
d5006255fd Added barrier.
[SVN r13581]
2002-04-29 16:19:27 +00:00
William E. Kempf
d7d8b4cedd Added thread_pool.
[SVN r13580]
2002-04-29 12:53:02 +00:00
nobody
c9f3478a21 This commit was manufactured by cvs2svn to create branch
'thread_development'.

[SVN r13571]
2002-04-26 21:15:41 +00:00
230 changed files with 16369 additions and 22903 deletions

2
build/.cvsignore Normal file
View File

@@ -0,0 +1,2 @@
bin*
*.pdb

68
build/Jamfile Normal file
View File

@@ -0,0 +1,68 @@
# (C) Copyright William E. Kempf 2001. Permission to copy, use, modify, sell and
# distribute this software is granted provided this copyright notice appears
# in all copies. This software is provided "as is" without express or implied
# warranty, and with no claim as to its suitability for any purpose.
#
# Boost.Threads build Jamfile
#
# Declares the following targets:
# 1. libboost_thread, a static link library.
# 1a. On Win32 (when PTW32 is not defined), a dynamic link library
# boost_threadmon, which must be used in conjunction with
# libboost_thread. Note that this DLL *must* be used through static
# linking to the import library. Dynamic loading will cause undefined
# behavior.
# Additional configuration variables used:
# 1. PTW32 may be used on Win32 platforms to specify that the pthreads-win32
# library should be used instead of "native" threads. This feature is
# mostly used for testing and it's generally recommended you use the
# native threading libraries instead. PTW32 should be set to be a list
# of two strings, the first specifying the installation path of the
# pthreads-win32 library and the second specifying which library
# variant to link against (see the pthreads-win32 documentation).
# Example: jam -sPTW32="c:\pthreads-win32 pthreadVCE.lib"
# Declare the location of this subproject relative to the root.
subproject libs/thread/build ;
# Include threads.jam for Boost.Threads global build information.
# This greatly simplifies the Jam code needed to configure the build
# for the various Win32 build types.
SEARCH on <module@>threads.jam = $(SUBDIR) ;
include <module@>threads.jam ;
template thread_libs
## sources ##
: <template>thread_base
## requirements ##
:
## default build ##
: debug release <runtime-link>static/dynamic
;
#######################
# Conditionally declare the Boost.Threads dynamic link library boost_threadmon.
if $(NT) && ! $(PTW32)
{
dll boost_threadmon : <template>thread_libs ../src/threadmon.cpp ;
}
#######################
# Declare the Boost.Threads static link library libboost_thread.
# Base names of the source files for libboost_thread.
CPP_SOURCES =
condition mutex recursive_mutex thread tss xtime once exceptions thread_pool barrier rw_mutex ;
lib boost_thread : <template>thread_libs ../src/$(CPP_SOURCES).cpp ;
#######################
# Stage the generated targets.
#stage bin-stage
# : <lib>boost_thread $(threadmon)
# : <tag><runtime-link-static>"s"
# <tag><debug>"d"
# : debug release <runtime-link>static/dynamic
#;

View File

@@ -1,207 +0,0 @@
# $Id$
# Copyright 2006-2007 Roland Schwarz.
# Copyright 2007 Anthony Williams
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
#########################################################################
# The boost threading library can be built on top of different API's
# Currently this is the win32 API and the pthreads API.
# Pthread is native on unix variants.
# To get pthread on windows you need the pthread win32 library
# http://sourceware.org/pthreads-win32 which is available under LGPL.
#
# You need to provide the include path and lib path in the variables
# PTW32_INCLUDE and PTW32_LIB respectively. You can specify these
# paths in site-config.jam, user-config.jam or in the environment.
# A new feature is provided to request a specific API:
# <threadapi>win32 and <threadapi)pthread.
#
# The naming of the resulting libraries is mostly the same for the
# variant native to the build platform, i.e.
# boost_thread and the boost specific tagging.
# For the library variant that is not native on the build platform
# an additional tag is applied:
# boost_thread_pthread for the pthread variant on windows, and
# boost_thread_win32 for the win32 variant (likely when built on cygwin).
#
# To request the pthread variant on windows, from boost root you would
# say e.g:
# bjam msvc-8.0 --with-thread install threadapi=pthread
#########################################################################
import os ;
import feature ;
import indirect ;
import path ;
project boost/thread
: source-location ../src
: requirements <threading>multi
<link>static:<define>BOOST_THREAD_BUILD_LIB=1
<link>shared:<define>BOOST_THREAD_BUILD_DLL=1
-<tag>@$(BOOST_JAMROOT_MODULE)%$(BOOST_JAMROOT_MODULE).tag
<tag>@$(__name__).tag
<toolset>gcc:<cxxflags>-Wno-long-long
: default-build <threading>multi
;
local rule default_threadapi ( )
{
local api = pthread ;
if [ os.name ] = "NT" { api = win32 ; }
return $(api) ;
}
feature.feature threadapi : pthread win32 : propagated ;
feature.set-default threadapi : [ default_threadapi ] ;
rule tag ( name : type ? : property-set )
{
local result = $(name) ;
if $(type) in STATIC_LIB SHARED_LIB IMPORT_LIB
{
local api = [ $(property-set).get <threadapi> ] ;
# non native api gets additional tag
if $(api) != [ default_threadapi ] {
result = $(result)_$(api) ;
}
}
# forward to the boost tagging rule
return [ indirect.call $(BOOST_JAMROOT_MODULE)%$(BOOST_JAMROOT_MODULE).tag
$(result) : $(type) : $(property-set) ] ;
}
rule win32_pthread_paths ( properties * )
{
local result ;
local PTW32_INCLUDE ;
local PTW32_LIB ;
PTW32_INCLUDE = [ modules.peek : PTW32_INCLUDE ] ;
PTW32_LIB = [ modules.peek : PTW32_LIB ] ;
PTW32_INCLUDE ?= [ modules.peek user-config : PTW32_INCLUDE ] ;
PTW32_LIB ?= [ modules.peek user-config : PTW32_LIB ] ;
PTW32_INCLUDE ?= [ modules.peek site-config : PTW32_INCLUDE ] ;
PTW32_LIB ?= [ modules.peek site-config : PTW32_LIB ] ;
if ! ( $(PTW32_INCLUDE) && $(PTW32_LIB) )
{
if ! $(.notified)
{
echo "************************************************************" ;
echo "Trying to build Boost.Thread with pthread support." ;
echo "If you need pthread you should specify the paths." ;
echo "You can specify them in site-config.jam, user-config.jam" ;
echo "or in the environment." ;
echo "For example:" ;
echo "PTW32_INCLUDE=C:\\Program Files\\ptw32\\Pre-built2\\include" ;
echo "PTW32_LIB=C:\\Program Files\\ptw32\\Pre-built2\\lib" ;
echo "************************************************************" ;
.notified = true ;
}
}
else
{
local include_path = [ path.make $(PTW32_INCLUDE) ] ;
local lib_path = [ path.make $(PTW32_LIB) ] ;
local libname = pthread ;
if <toolset>msvc in $(properties)
{
libname = $(libname)VC2.lib ;
}
if <toolset>gcc in $(properties)
{
libname = lib$(libname)GC2.a ;
}
lib_path = [ path.glob $(lib_path) : $(libname) ] ;
if ! $(lib_path)
{
if ! $(.notified)
{
echo "************************************************************" ;
echo "Trying to build Boost.Thread with pthread support." ;
echo "But the library" $(libname) "could not be found in path" ;
echo $(PTW32_LIB) ;
echo "************************************************************" ;
.notified = true ;
}
}
else
{
result += <include>$(include_path) ;
result += <library>$(lib_path) ;
}
}
return $(result) ;
}
rule usage-requirements ( properties * )
{
local result ;
if <threadapi>pthread in $(properties)
{
result += <define>BOOST_THREAD_POSIX ;
if <target-os>windows in $(properties)
{
result += [ win32_pthread_paths $(properties) ] ;
# TODO: What is for static linking? Is the <library> also needed
# in that case?
}
}
return $(result) ;
}
rule requirements ( properties * )
{
local result ;
if <threadapi>pthread in $(properties)
{
result += <define>BOOST_THREAD_POSIX ;
if <target-os>windows in $(properties)
{
local paths = [ win32_pthread_paths $(properties) ] ;
if $(paths)
{
result += $(paths) ;
}
else
{
result = <build>no ;
}
}
}
return $(result) ;
}
alias thread_sources
: ## win32 sources ##
win32/thread.cpp
win32/tss_dll.cpp
win32/tss_pe.cpp
: ## requirements ##
<threadapi>win32
;
alias thread_sources
: ## pthread sources ##
pthread/thread.cpp
pthread/once.cpp
: ## requirements ##
<threadapi>pthread
;
explicit thread_sources ;
lib boost_thread
: thread_sources
: <conditional>@requirements
:
: <link>shared:<define>BOOST_THREAD_USE_DLL=1
<link>static:<define>BOOST_THREAD_USE_LIB=1
<conditional>@usage-requirements
;

32
build/threads.jam Normal file
View File

@@ -0,0 +1,32 @@
# Do some OS-specific setup
threadmon = ;
pthreads-win32 = ;
if $(NT)
{
if $(PTW32)
{
local install-path = $(PTW32[1]) ;
local lib = $(PTW32[2]) ;
pthreads-win32 =
<define>BOOST_HAS_PTHREADS
<define>PtW32NoCatchWarn
<include>$(install-path)/pre-built/include
<library-file>$(install-path)/pre-built/lib/$(lib)
;
}
else
{
threadmon = <dll>../build/boost_threadmon ;
}
}
template thread_base
## sources ##
:
## requirements ##
: <sysinclude>$(BOOST_ROOT) <threading>multi $(pthreads-win32)
## default build ##
:
;

BIN
build/threads.mcp Normal file

Binary file not shown.

View File

@@ -1,31 +0,0 @@
# (C) Copyright 2008 Anthony Williams
#
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
path-constant boost-images : ../../../doc/src/images ;
xml thread : thread.qbk ;
boostbook standalone
:
thread
:
# HTML options first:
# Use graphics not text for navigation:
<xsl:param>navig.graphics=1
# How far down we chunk nested sections, basically all of them:
<xsl:param>chunk.section.depth=3
# Don't put the first section on the same page as the TOC:
<xsl:param>chunk.first.sections=1
# How far down sections get TOC's
<xsl:param>toc.section.depth=10
# Max depth in each TOC:
<xsl:param>toc.max.depth=3
# How far down we go with TOC's
<xsl:param>generate.section.toc.level=10
# Path for links to Boost:
<xsl:param>boost.root=../../../..
;

View File

@@ -1,23 +0,0 @@
[/
(C) Copyright 2007-8 Anthony Williams.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
]
[section:acknowledgements Acknowledgments]
The original implementation of __boost_thread__ was written by William Kempf, with contributions from numerous others. This new
version initially grew out of an attempt to rewrite __boost_thread__ to William Kempf's design with fresh code that could be
released under the Boost Software License. However, as the C++ Standards committee have been actively discussing standardizing a
thread library for C++, this library has evolved to reflect the proposals, whilst retaining as much backwards-compatibility as
possible.
Particular thanks must be given to Roland Schwarz, who contributed a lot of time and code to the original __boost_thread__ library,
and who has been actively involved with the rewrite. The scheme for dividing the platform-specific implementations into separate
directories was devised by Roland, and his input has contributed greatly to improving the quality of the current implementation.
Thanks also must go to Peter Dimov, Howard Hinnant, Alexander Terekhov, Chris Thomasson and others for their comments on the
implementation details of the code.
[endsect]

73
doc/acknowledgments.html Normal file
View File

@@ -0,0 +1,73 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Acknowledgments</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Acknowledgments</h2>
</td>
</tr>
</table>
<hr>
<p><a href="../../../people/william_kempf.htm">William E. Kempf</a> was the architect,
designer, and implementor of <b>Boost.Threads</b>.</p>
<p>Mac OS Carbon implementation written by <a href="../../../people/mac_murrett.htm">Mac
Murrett</a>.</p>
<p><a href="mailto:jdmoore99@comcast.net">Dave Moore</a> provided initial submissions
and further comments on the <code>barrier</code>, <code>thread_pool</code>,
<code>rw_mutex</code>, <code>rw_try_mutex</code> and <code>rw_timed_mutex</code>
classes.</p>
<p>Important contributions were also made by Jeremy Siek (lots of input on the
design and on the implementation), Alexander Terekhov (lots of input on the
Win32 implementation, especially in regards to boost::condition, as well as
a lot of explanation of POSIX behavior), Greg Colvin (lots of input on the design),
Paul Mclachlan, Thomas Matelich and Iain Hanson (for help in trying to get the
build to work on other platforms), and Kevin S. Van Horn (for several updates/corrections
to the documentation).</p>
<p>The documentation was written by William E. Kempf. Beman Dawes provided additional
documentation material and editing.</p>
<p>Discussions on the boost.org mailing list were essential in the development
of <b>Boost.Threads</b>. As of August 1, 2001, participants included Alan Griffiths,
Albrecht Fritzsche, Aleksey Gurtovoy, Alexander Terekhov, Andrew Green, Andy
Sawyer, Asger Alstrup Nielsen, Beman Dawes, Bill Klein, Bill Rutiser, Bill Wade,
Branko &Egrave;ibej, Brent Verner, Craig Henderson, Csaba Szepesvari, Dale Peakall,
Damian Dixon, Dan Nuffer, Darryl Green, Daryle Walker, David Abrahams, David
Allan Finch, Dejan Jelovic, Dietmar Kuehl, Doug Gregor, Douglas Gregor, Duncan
Harris, Ed Brey, Eric Swanson, Eugene Karpachov, Fabrice Truillot, Frank Gerlach,
Gary Powell, Gernot Neppert, Geurt Vos, Ghazi Ramadan, Greg Colvin, Gregory
Seidman, HYS, Iain Hanson, Ian Bruntlett, J Panzer, Jeff Garland, Jeff Paquette,
Jens Maurer, Jeremy Siek, Jesse Jones, Joe Gottman, John (EBo) David, John Bandela,
John Maddock, John Max Skaller, John Panzer, Jon Jagger , Karl Nelson, Kevlin
Henney, KG Chandrasekhar, Levente Farkas, Lie-Quan Lee, Lois Goldthwaite, Luis
Pedro Coelho, Marc Girod, Mark A. Borgerding, Mark Rodgers, Marshall Clow, Matthew
Austern, Matthew Hurd, Michael D. Crawford, Michael H. Cox , Mike Haller, Miki
Jovanovic, Nathan Myers, Paul Moore, Pavel Cisler, Peter Dimov, Petr Kocmid,
Philip Nash, Rainer Deyke, Reid Sweatman, Ross Smith, Scott McCaskill, Shalom
Reich , Steve Cleary, Steven Kirk, Thomas Holenstein, Thomas Matelich, Trevor
Perrin, Valentin Bonnard, Vesa Karvonen, Wayne Miller, and William Kempf.</p>
<p>Apologies for anyone inadvertently missed.</p>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

168
doc/barrier.html Normal file
View File

@@ -0,0 +1,168 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Header &lt;boost/thread/barrier.hpp&gt;</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Header &lt;<a href="../../../boost/thread/barrier.hpp">boost/thread/barrier.hpp</a>&gt;</h2>
</td>
</tr>
</table>
<hr>
<h2>Contents</h2>
<dl class="page-index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#classes">Classes</a></dt>
<dl class="page-index">
<dt><a href="#class-barrier">Class <code>barrier</code></a></dt>
<dl class="page-index">
<dt><a href="#class-barrier-synopsis">Class <code>barrier</code> synopsis</a></dt>
<dt><a href="#class-barrier-ctors">Class <code>barrier</code> constructors
and destructor</a></dt>
<dt><a href="#class-barrier-modifiers">Class <code>barrier</code> modifier
functions</a></dt>
</dl>
</dl>
<dt><a href="#examples">Example(s)</a></dt>
</dl>
<hr>
<h2><a name="introduction"></a>Introduction</h2>
<p>Include the header &lt;<a href="../../../boost/thread/barrier.hpp">boost/thread/barrier.hpp</a>&gt;
to define the class <code>boost::barrier</code>.</p>
<h2><a name="classes"></a>Classes</h2>
<h3><a name="class-barrier"></a>Class <code>barrier</code></h3>
<p>An object of class <code>barrier</code> is a synchronization primitive used
to cause a set of threads to wait until they each perform a certain function
or each reach a particular point in their execution. When a barrier is created,
it is initialized with a thread count "N". The first N-1 calls to wait() will
all cause their threads to be blocked. The Nth call to wait() will allow all
of the waiting threads, including the Nth thread, to be placed in a ready state.
Should an additional thread make an N+1th call to wait() on the barrier, it
will be as though this was the first call to wait(), and the process will be
repeated until another N threads call wait(). This functionality allows the
same set of N threads to re-use a barrier object to synchronize their execution
at multiple points during their execution.</p>
<p>See <A href="definitions.html">Formal Definitions</A> for definitions of thread
states <A href="definitions.html#state">blocked</A> and <A href="definitions.html#state">
ready</A>. Note that "waiting" is a synonym for blocked.</p>
<h4><a name="class-barrier-synopsis"></a>Class <code>barrier</code> synopsis</h4>
<pre>
namespace boost
{
class barrier : private <A href="../../utility/utility.htm#Class noncopyable">boost::noncopyable</A> // Exposition only.
// Class barrier meets the <A href="overview.html#NonCopyable" .. utility.htm#Class? utility>NonCopyable</A> requirement.
{
public:
barrier(size_t count);
~barrier();
bool wait();
};
};
</pre>
<h4><a name="class-barrier-ctors"></a>Class <code>barrier</code> constructors
and destructor</h4>
<pre>
barrier(size_t count);
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Constructs a <code>barrier</code> object that will cause
count threads to block on a call to <code>wait()</code>.</dt>
</dl>
<pre>
~barrier();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Destroys <code>*this</code>. If threads are still executing
their <code>wait()</code> operations, the behavior for these threads is undefined.</dt>
</dl>
<h4><a name="class-barrier-modifiers"></a>Class <code>barrier</code> modifier
functions</h4>
<pre>
bool wait();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Wait until N threads call wait(), where N equals the count
provided to the constructor for the barrier object.</dt>
<dt><b>Returns:</b> Exactly one of the N threads will receive a return value
of <code>true</code>, the others will receive a value of <code>false</code>.
Precisely which thread receives the return value of <code>true</code> will
be implementation defined. Applications can use this value to designate one
thread as a leader that will take a certain action, and the other threads
emerging from the barrier can wait for that action to take place.</dt>
<dt><b>Danger:</b> If the barrier is destroyed before <code>wait()</code> can
return, the behavior is undefined.</dt>
</dl>
<h2><a name="examples"></a>Example(s)</h2>
<pre>
#include <a href="../../../boost/thread/condition.hpp">&lt;boost/thread/barrier.hpp&gt;</a>
#include <a href="../../../boost/thread/thread.hpp">&lt;boost/thread/thread.hpp&gt;</a>
#include <a href="../../../boost/thread/mutex.hpp">&lt;boost/thread/mutex.hpp&gt;</a>
#include &lt;iostream&gt;
const int N_THREADS = 10;
boost::barrier gen_barrier(N_THREADS);
int global_parameter = 0;
boost::mutex mutex;
static void worker()
{
for (int i = 0; i &lt; 5; ++i)
{
// Simulate 5 cycles of computation...
if (gen_barrier.wait())
{
boost::mutex::scoped_lock lock(mutex);
global_parameter++;
}
}
// Let one worker "report" the results
if (gen_barrier.wait())
{
boost::mutex::scoped_lock lock(lock);
std::cout &lt;&lt; "Global Parameter=" &lt;&lt; global_parameter &lt;&lt; "\n";
}
}
int main(int, char*[])
{
boost::thread_group g;
global_parameter = 0;
for (int i = 0; i &lt; N_THREADS; ++i)
g.create_thread(&amp;worker);
g.join_all();
}
</pre>
<p>The output is:</p>
<pre>
Global Parameter=5
</pre>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:jdmoore99@comcast.net">Dave Moore</a> and <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

View File

@@ -1,72 +0,0 @@
[/
(C) Copyright 2007-8 Anthony Williams.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
]
[section:barriers Barriers]
A barrier is a simple concept. Also known as a ['rendezvous], it is a synchronization point between multiple threads. The barrier is
configured for a particular number of threads (`n`), and as threads reach the barrier they must wait until all `n` threads have
arrived. Once the `n`-th thread has reached the barrier, all the waiting threads can proceed, and the barrier is reset.
[section:barrier Class `barrier`]
#include <boost/thread/barrier.hpp>
class barrier
{
public:
barrier(unsigned int count);
~barrier();
bool wait();
};
Instances of __barrier__ are not copyable or movable.
[heading Constructor]
barrier(unsigned int count);
[variablelist
[[Effects:] [Construct a barrier for `count` threads.]]
[[Throws:] [__thread_resource_error__ if an error occurs.]]
]
[heading Destructor]
~barrier();
[variablelist
[[Precondition:] [No threads are waiting on `*this`.]]
[[Effects:] [Destroys `*this`.]]
[[Throws:] [Nothing.]]
]
[heading Member function `wait`]
bool wait();
[variablelist
[[Effects:] [Block until `count` threads have called `wait` on `*this`. When the `count`-th thread calls `wait`, all waiting threads
are unblocked, and the barrier is reset. ]]
[[Returns:] [`true` for exactly one thread from each batch of waiting threads, `false` otherwise.]]
[[Throws:] [__thread_resource_error__ if an error occurs.]]
]
[endsect]
[endsect]

165
doc/bibliography.html Normal file
View File

@@ -0,0 +1,165 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Bibliography</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Bibliography</h2>
</td>
</tr>
</table>
<hr>
<table summary="Bibliography" border="0" cellpadding="5" width="777">
<tr>
<td width="102" valign="top" align="left"><b>[<a name=
"Andrews-83">Andrews 83</a>]</b></td>
<td width="645"> Gregory R. Andrews, Fred B. Schneider, <cite>Concepts and
Notations for Concurrent Programming</cite>, ACM Computing Surveys, Vol.
15, No. 1, March, 1983. <a href=
"http://www.acm.org/pubs/citations/journals/surveys/1983-15-1/p3-andrews/">
http://www.acm.org/pubs/citations/journals/surveys/1983-15-1/p3-andrews/</a>
<p>Good general background reading. Includes descriptions of Path Expressions,
Message Passing, and Remote Procedure Call in addition to the basics.</p>
</td>
</tr>
<tr>
<td width="102" valign="top" align="left"><b>[<a name=
"Boost">Boost</a>]</b></td>
<td width="645"> The <cite>Boost</cite> worldwide web site. <a href=
"http://www.boost.org">http://www.boost.org</a>
<p>Boost.Threads is one of many Boost libraries. The Boost web site includes
a great deal of documentation and general information which applies to
all Boost libraries. Current copies of the libraries including documentation
and test programs may be downloaded from the web site.</p>
</td>
</tr>
<tr>
<td width="102" valign="top" align="left"><b>[<a name=
"Brinch-Hansen-73">Brinch Hansen 73</a>]</b></td>
<td width="645"> Per Brinch Hansen, <cite>Concurrent Programming Concepts</cite>,
ACM Computing Surveys, Vol. 5, No. 4, December, 1973. <a href=
"http://www.acm.org/pubs/articles/journals/surveys/1973-5-4/p223-hansen/p223-hansen.pdf">
http://www.acm.org/pubs/articles/journals/surveys/1973-5-4/p223-hansen/</a>
<p>&quot;This paper describes the evolution of language features for multiprogramming
from event queues and semaphores to critical regions and monitors.&quot;
Includes analysis of why <i>events</i> are considered error-prone. Also
noteworthy because of an introductory quotation from Christopher Alexander;
Brinch Hansen was years ahead of others in recognizing pattern concepts
applied to software too.</p>
</td>
</tr>
<tr>
<td width="102" valign="top" align="left"><b>]<a name=
"Butenhof-97">Butenhof 97</a>]</b></td>
<td width="645">
<p>David R. Butenhof, <cite>Programming with POSIX Threads</cite>, Addison-Wesley
1997, ISBN 0-201-63392-2 <a
href="http://cseng.aw.com/book/0,3828,0201633922,00.html">
http://cseng.aw.com/book/0,3828,0201633922,00.html</a></p>
<p>This is a very readable explanation of threads and how to use them. Many
of the insights given apply to all multithreaded programming, not just
POSIX Threads.</p>
</td>
</tr>
<tr>
<td width="102" valign="top" align="left"><b>[<a name=
"Hoare-74">Hoare 74</a>]</b></td>
<td width="645">
<p>C.A.R Hoare, <cite>Monitors: An Operating System Structuring Concept</cite>,
Communications of the ACM, Vol. 17, No. 10. October 1974, pp. 549-557
<a href=
"http://www.acm.org/classics/feb96/"> http://www.acm.org/classics/feb96/</a></p>
<p>Hoare and Brinch Hansen&#39;s work on Monitors is the basis for reliable
multithreading patterns. This is one of the most often referenced papers
in all of computer science, and with good reason.</p>
</td>
</tr>
<tr>
<td width="102" valign="top" align="left"><b>[<a name=
"ISO-98">ISO 98</a>]</b></td>
<td width="645">
<p>ISO/IEC 14882:1998(E) <cite>Programming Language C++</cite> <a href="http://www.ansi.org">
http://www.ansi.org</a></p>
<p>This is the official C++ Standards document. Available from the ANSI
(American National Standards Institute) Electronic Standards Store.</p>
</td>
</tr>
<tr>
<td width="102" valign="top" align="left"><b>[<a name=
"McDowell-89">McDowell 89</a>]</b></td>
<td width="645"> Charles E McDowell, David P. Helmbold, <cite>Debugging Concurrent
Programs</cite>, ACM Computing Surveys, Vol. 21, No. 2, December, 1989.
<a href=
"http://www.acm.org/pubs/citations/journals/surveys/1989-21-4/p593-mcdowell/">
http://www.acm.org/pubs/citations/journals/surveys/1989-21-4/p593-mcdowell/</a>
<p>Identifies many of the unique failure modes and debugging difficulties
associated with concurrent programs.</p>
</td>
</tr>
<tr>
<td width="102" valign="top" align="left"><b>[<a name=
"Schmidt">Schmidt</a>]</b> </td>
<td width="645">
<p>Douglas C. Schmidt and Irfan Pyarali, <cite>Strategies for Implementing
POSIX Condition Variables on Win32</cite>, Department of Computer Science,
Washington University, St. Louis, Missouri. <a href=
"http://www.cs.wustl.edu/~schmidt/win32-cv-1.html"> http://www.cs.wustl.edu/~schmidt/win32-cv-1.html</a></p>
<p>Rationale for understanding Boost.Threads condition variables. Note that
Alexander Terekhov found some bugs in the implementation given in this
article, so pthreads-win32 and Boost.Threads are even more complicated
yet.</p>
</td>
</tr>
<tr>
<td width="102" valign="top" align="left"><b>[<a name=
"Schmidt-00">Schmidt 00</a>]</b> </td>
<td width="645">
<p>Douglas C. Schmidt, Michael Stal, Hans Rohnert and Frank Buschmann, <cite>Pattern-Oriented
Software Architecture Volume 2 - Patterns for Concurrent and Networked
Objects</cite>, Wiley 2000, ISBN 0-471-60695-2 <a href=
"http://www.wiley.com/Corporate/Website/Objects/Products/0,9049,104671,00.html">
http://www.wiley.com/Corporate/Website/Objects/Products/0,9049,104671,00.html</a></p>
<p>This is a very good explanation of how to apply several patterns useful
for concurrent programming. Among the patterns documented is the Monitor
Pattern mentioned frequently in the <b>Boost.Threads</b> documentation.</p>
</td>
</tr>
<tr>
<td width="102" valign="top" align="left"><b>[<a name=
"Stroustrup-00">Stroustrup 00</a>]</b></td>
<td width="645"> Bjarne Stroustrup, <cite>The C++ Programming Language</cite>,
Special Edition, Addison-Wesley 2000, ISBN 0-201-70073-5 <a href=
"http://cseng.aw.com/book/0,3828,0201700735,00.html"> http://cseng.aw.com/book/0,3828,0201700735,00.html</a>
<p>The first book a C++ programmer should own. Note that the 3rd edition
(and subsequent editions like the Special Edition) has been rewritten
to cover the ISO standard language and library.</p>
</td>
</tr>
</table>
<p>Note: The URL&#39;s above are provided in plain text form so that they will
be visible on printed copies of this document.</p>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> and
Beman Dawes 2001-2002. All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

77
doc/build.html Normal file
View File

@@ -0,0 +1,77 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>{{Library}} - Overview</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Building and Testing</h2>
</td>
</tr>
</table>
<hr>
<dl class="index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#topic1">First topic</a></dt>
<dt><a href="#topic2">Second topic</a></dt>
<dt><a href="#footnotes">Footnotes</a></dt>
</dl>
<h2><a name="introduction"></a>Introduction</h2>
<p>How you build the Boost.Threads libraries, and how you build your own applications
that use those libraries, are some of the most frequently asked questions. Build
processes are difficult to deal with in a portable manner. That's one reason
why Boost.Threads makes use of <a href="../../../tools/build/index.html">Boost.Build</a>.
In general you should refer to the documentation for <a href="../../../tools/build/index.html">Boost.Build</a>.
This document will only supply you with some simple usage examples for how to
use <em>bjam</em> to build and test Boost.Threads. In addition, this document
will try and explain the build requirements so that users may create their own
build processes (for instance, create an IDE specific project), both for building
and testing Boost.Threads, as well as for building their own projects using
Boost.Threads. </p>
<h2><a name="topic1"></a>Building the Boost.Threads Libraries</h2>
<p>To build the Boost.Thread libraries using Boost.Build, simply change to the
directory <em>boost_root</em>/libs/thread/build and execute the command:</p>
<pre>bjam -sTOOLS=<em>toolset</em></pre>
<p>This will create four variants of the Boost.Threads library with the permuations
of debug/release and runtime-link-dynamic/runtime-link-static. <em><strong>Note:</strong></em>
Invoking the above command in <em>boost_root</em> will build all of the Boost
distribution, including Boost.Threads.</p>
<p>The Jamfile supplied with Boost.Threads produces a static library named <em>libboostthread</em>.
In addition, on Win32 platforms a <em>boostthreadmon.dll</em> and a coresponding
import library are created. The source files that are used to create the <em>libboostthread</em>
library are all of the *.cpp files found in <em>boost_root</em>/libs/thread/src,
except for <em>threadmon.cpp</em>. These need to be built with the compiler's
and linker's multi-threading support enabled. On Win32 platforms the <em>boostthreadmon.dll</em>
is created from <em>boost_root</em>/libs/thread/src/threadmon.cpp. This, too,
needs to be built with the compiler's and linker's multi-threading support enabled.
If you want to create your own build solution you'll have to follow these same
guidelines. One of the most frequently reported problems when trying to do this
occurs from not enabling the compiler's and linker's support for multi-threading.</p>
<h2><a name="topic2"></a>Testing the Boost.Threads Libraries</h2>
<p>To test the Boost.Threads libraries using Boost.Build, simply change to the
directory <em>boost_root</em>/libs/thread/test and execute the command:</p>
<pre><code>bjam -sTOOLS=<em>toolset</em> test</code></pre>
<p> </p>
<h2><a name="footnotes"></a>Footnotes</h2>
<dl>
<dt><a name="footnote1" class="footnote">(1)</a> {{text}}</dt>
<dt><a name="footnote2" class="footnote">(2)</a> {{text}}</dt>
</dl>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:{{address}}">{{author}}</a>
2002. All Rights Reserved.</i></p>
</body>
</html>

View File

@@ -1,87 +0,0 @@
[/
(C) Copyright 2007-8 Anthony Williams.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
]
[section:changes Changes since boost 1.40]
The 1.41.0 release of Boost adds futures to the thread library. There are also a few minor changes.
[heading Changes since boost 1.35]
The 1.36.0 release of Boost includes a few new features in the thread library:
* New generic __lock_multiple_ref__ and __try_lock_multiple_ref__ functions for locking multiple mutexes at once.
* Rvalue reference support for move semantics where the compilers supports it.
* A few bugs fixed and missing functions added (including the serious win32 condition variable bug).
* `scoped_try_lock` types are now backwards-compatible with Boost 1.34.0 and previous releases.
* Support for passing function arguments to the thread function by supplying additional arguments to the __thread__ constructor.
* Backwards-compatibility overloads added for `timed_lock` and `timed_wait` functions to allow use of `xtime` for timeouts.
[heading Changes since boost 1.34]
Almost every line of code in __boost_thread__ has been changed since the 1.34 release of boost. However, most of the interface
changes have been extensions, so the new code is largely backwards-compatible with the old code. The new features and breaking
changes are described below.
[heading New Features]
* Instances of __thread__ and of the various lock types are now movable.
* Threads can be interrupted at __interruption_points__.
* Condition variables can now be used with any type that implements the __lockable_concept__, through the use of
`boost::condition_variable_any` (`boost::condition` is a `typedef` to `boost::condition_variable_any`, provided for backwards
compatibility). `boost::condition_variable` is provided as an optimization, and will only work with
`boost::unique_lock<boost::mutex>` (`boost::mutex::scoped_lock`).
* Thread IDs are separated from __thread__, so a thread can obtain it's own ID (using `boost::this_thread::get_id()`), and IDs can
be used as keys in associative containers, as they have the full set of comparison operators.
* Timeouts are now implemented using the Boost DateTime library, through a typedef `boost::system_time` for absolute timeouts, and
with support for relative timeouts in many cases. `boost::xtime` is supported for backwards compatibility only.
* Locks are implemented as publicly accessible templates `boost::lock_guard`, `boost::unique_lock`, `boost::shared_lock`, and
`boost::upgrade_lock`, which are templated on the type of the mutex. The __lockable_concept__ has been extended to include publicly
available __lock_ref__ and __unlock_ref__ member functions, which are used by the lock types.
[heading Breaking Changes]
The list below should cover all changes to the public interface which break backwards compatibility.
* __try_mutex__ has been removed, and the functionality subsumed into __mutex__. __try_mutex__ is left as a `typedef`,
but is no longer a separate class.
* __recursive_try_mutex__ has been removed, and the functionality subsumed into
__recursive_mutex__. __recursive_try_mutex__ is left as a `typedef`, but is no longer a separate class.
* `boost::detail::thread::lock_ops` has been removed. Code that relies on the `lock_ops` implementation detail will no longer work,
as this has been removed, as it is no longer necessary now that mutex types now have public __lock_ref__ and __unlock_ref__ member
functions.
* `scoped_lock` constructors with a second parameter of type `bool` are no longer provided. With previous boost releases,
``boost::mutex::scoped_lock some_lock(some_mutex,false);`` could be used to create a lock object that was associated with a mutex,
but did not lock it on construction. This facility has now been replaced with the constructor that takes a
`boost::defer_lock_type` as the second parameter: ``boost::mutex::scoped_lock some_lock(some_mutex,boost::defer_lock);``
* The `locked()` member function of the `scoped_lock` types has been renamed to __owns_lock_ref__.
* You can no longer obtain a __thread__ instance representing the current thread: a default-constructed __thread__ object is not
associated with any thread. The only use for such a thread object was to support the comparison operators: this functionality has
been moved to __thread_id__.
* The broken `boost::read_write_mutex` has been replaced with __shared_mutex__.
* __mutex__ is now never recursive. For Boost releases prior to 1.35 __mutex__ was recursive on Windows and not on POSIX platforms.
* When using a __recursive_mutex__ with a call to [cond_any_wait_link `boost::condition_variable_any::wait()`], the mutex is only
unlocked one level, and not completely. This prior behaviour was not guaranteed and did not feature in the tests.
[endsect]

225
doc/condition.html Normal file
View File

@@ -0,0 +1,225 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Header &lt;boost/thread/condition.hpp&gt;</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Header &lt;<a href="../../../boost/thread/condition.hpp">boost/thread/condition.hpp</a>&gt;</h2>
</td>
</tr>
</table>
<hr>
<h2>Contents</h2>
<dl class="page-index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#classes">Classes</a></dt>
<dl class="page-index">
<dt><a href="#class-condition">Class <code>condition</code></a></dt>
<dl class="page-index">
<dt><a href="#class-condition-synopsis">Class <code>condition</code> synopsis</a></dt>
<dt><a href="#class-condition-ctors">Class <code>condition</code> constructors
and destructor</a></dt>
<dt><a href="#class-condition-modifiers">Class <code>condition</code> modifier
functions</a></dt>
</dl>
</dl>
<dt><a href="#examples">Example(s)</a></dt>
</dl>
<hr>
<h2><a name="introduction"></a>Introduction</h2>
<p>Include the header &lt;<a href="../../../boost/thread/condition.hpp">boost/thread/condition.hpp</a>&gt;
to define the class condition.</p>
<h2><a name="classes"></a>Classes</h2>
<h3><a name="class-condition"></a>Class <code>condition</code></h3>
<p>An object of class <code>condition</code> is a synchronization primitive used
to cause a thread to wait until a particular shared-data condition (or time)
is met. A <code>condition</code> object is always used in conjunction with a
mutex object (an object whose type is a model of <a href="mutex_concept.html">Mutex</a>
or one of its refinements). The mutex object must be locked prior to waiting
on the <code>condition</code>, which is verified by passing a lock object (an
object whose type is a model of <a href="lock_concept.html">Lock</a> or one
of its refinements) to the <code>condition</code> object&#39;s <code>wait</code>
functions. Upon blocking on the condition object, the thread unlocks the mutex
object. When the thread returns from a call to one of the condition object's
wait functions the mutex object is again locked. The tricky unlock/lock sequence
is performed automatically by the <code> condition</code> object&#39;s <code>wait</code>
functions.</p>
<p>The <code>condition</code> type is often used to implement the <i> Monitor
Object</i> and other important patterns (see <a href="bibliography.html#Schmidt-00">[Schmidt
00]</a> and <a href="bibliography.html#Hoare-74">[Hoare 74]</a>). Monitors are
one of the most important patterns for creating reliable multithreaded programs.</p>
<p>See <a href="definitions.html">Formal Definitions</a> for definitions of thread
states <a href="definitions.html#state"> blocked</a> and <a href="definitions.html#state">ready</a>.
Note that &quot;waiting&quot; is a synonym for blocked.</p>
<h4><a name="class-condition-synopsis"></a>Class <code>condition</code> synopsis</h4>
<pre>
namespace boost
{
class condition : private <a href="../../utility/utility.htm#Class noncopyable">boost::noncopyable</a> // Exposition only.
// Class condition meets the <a href="overview.html#non-copyable">NonCopyable</a> requirement.
{
public:
condition();
~condition();
void notify_one();
void notify_all();
template &lt;typename <a href="lock_concept.html#Lock-concept">Lock</a>&gt;
void wait(<a href="lock_concept.html#Lock-concept">Lock</a>&amp; lock);
template &lt;typename <a href="lock_concept.html#Lock-concept">Lock</a>, typename <a href="http://www.sgi.com/tech/stl/Predicate.html">Predicate</a>&gt;
void wait(<a href="lock_concept.html#Lock-concept">Lock</a>&amp; lock, <a href="http://www.sgi.com/tech/stl/Predicate.html">Predicate</a> pred);
template &lt;typename <a href="lock_concept.html#Lock-concept">Lock</a>&gt;
bool timed_wait(<a href="lock_concept.html#Lock-concept">Lock</a>&amp; lock, const xtime&amp; xt);
template &lt;typename <a href="lock_concept.html#Lock-concept">Lock</a>, typename <a href="http://www.sgi.com/tech/stl/Predicate.html">Predicate</a>&gt;
bool timed_wait(<a href="lock_concept.html#Lock-concept">Lock</a>&amp; lock, const xtime&amp; XT, <a href="http://www.sgi.com/tech/stl/Predicate.html">Predicate</a> pred);
};
};
</pre>
<h4><a name="class-condition-ctors"></a>Class <code>condition</code> constructors
and destructor</h4>
<pre>
condition();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Constructs a <code>condition</code> object.</dt>
</dl>
<pre>
~condition();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Destroys <code>*this</code>.</dt>
</dl>
<h4><a name="class-condition-modifiers"></a>Class <code>condition</code> modifier
functions</h4>
<pre>
void notify_one();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> If there is a thread waiting on <code>*this</code>, change
that thread&#39;s state to ready. Otherwise there is no effect.</dt>
<dt><b>Note:</b> If more than one thread is waiting on the condition, it is
unspecified which is made ready. After returning to a ready state the notified
thread must still acquire the mutex again (which occurs within the call to
one of the <code>condition</code> object's wait functions).</dt>
</dl>
<pre>
void notify_all();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Change the state of all threads waiting on <code> *this</code>
to ready. If there are no waiting threads, <code> notify_all()</code> has
no effect.</dt>
</dl>
<pre>
template &lt;typename ScopedLock&gt;
void wait(ScopedLock&amp; lock);
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> <code>ScopedLock</code> meets the <a href="lock_concept.html#ScopedLock">ScopedLock</a>
requirements.</dt>
<dt><b>Effects:</b> Releases the lock on the <a href="mutex_concept.html">mutex
model</a> associated with <code>lock</code>, blocks the current thread of
execution until readied by a call to <code>this-&gt;notify_one()</code> or
<code> this-&gt;notify_all()</code>, and then reacquires the lock.</dt>
<dt><b>Throws:</b> <code><a href="exceptions.html#class-lock_error">lock_error</a></code>
if <code>!lock.locked()</code></dt>
<dt><b>Danger:</b> This version should always be used within a loop checking
that the state logically associated with the <code>condition</code> has become
true. Without the loop, race conditions can ensue due to possible &quot;spurious
wake ups&quot;. The second version encapsulates this loop idiom internally
and is generally the preferred method.</dt>
</dl>
<pre>
Template&lt;typename ScopedLock, typename Pr&gt;
void wait(ScopedLock&amp; lock, Pr pred);
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> <code>ScopedLock</code> meets the <a href="lock_concept.html#ScopedLock">ScopedLock</a>
requirements, return from <code>pred()</code> convertible to bool.</dt>
<dt><b>Effects:</b> As if: <code>while (!pred()) wait(lock)</code></dt>
<dt><b>Throws:</b> <code><a href="exceptions.html#class-lock_error">lock_error</a></code>
if <code>!lock.locked()</code></dt>
</dl>
<pre>
template &lt;typename ScopedLock&gt;
bool timed_wait(ScopedLock&amp; lock, const <a href="xtime.html">xtime</a>&amp; XT);
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> <code>ScopedLock</code> meets the <a href="lock_concept.html#ScopedLock">ScopedLock</a>
requirements.</dt>
<dt><b>Effects:</b> Releases the lock on the <a href="mutex_concept.html">mutex
model</a> associated with the <code> lock</code>, blocks the current thread
of execution until readied by a call to <code>this-&gt;notify_one()</code>
or <code> this-&gt;notify_all()</code>, or until <code>XT</code>, and then
reacquires the lock.</dt>
<dt><b>Returns:</b> <code>false</code> if <code>XT</code> is reached, otherwise
<code>true</code>.</dt>
<dt><b>Throws:</b> <code><a href="exceptions.html#class-lock_error">lock_error</a></code>
if <code>!lock.locked()</code></dt>
<dt><b>Danger:</b> This version should always be used within a loop checking
that the state logically associated with the <code>condition</code> has become
true. Without the loop, race conditions can ensue due to &quot;spurious wake
ups&quot;. The second version encapsulates this loop idiom internally and
is generally the preferred method.</dt>
</dl>
<pre>
Template&lt;typename ScopedLock, typename Pr&gt;
bool timed_wait(ScopedLock&amp; lock, const <a href="xtime.html">xtime</a>&amp; XT, Pr pred);
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> <code>ScopedLock</code> meets the <a href="lock_concept.html#ScopedLock">ScopedLock</a>
requirements, return from <code>pred()</code> convertible to bool.</dt>
<dt><b>Effects:</b> As if:<br>
<pre>
while (!pred())
{
if (!timed_wait(lock, XT))
return false;
}
return true;
</pre>
</dt>
<dt><b>Returns:</b> <code>false</code> if <code>XT</code> is reached, otherwise
<code>true</code>.</dt>
<dt><b>Throws:</b> <code><a href="exceptions.html#class-lock_error">lock_error</a></code>
if <code>!lock.locked()</code></dt>
</dl>
<h2><a name="examples"></a>Example(s)</h2>
<p><a href="../example/condition.cpp">libs/thread/example/condition.cpp</a></p>
<p>Typical output (dependent on scheduling policies) is:</p>
<pre>
sent: 0
sent: 1
received: 0
received: 1
sent: 2
sent: 3
received: 2
received: 3
sent: 4
received: 4
</pre>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

View File

@@ -1,513 +0,0 @@
[/
(C) Copyright 2007-8 Anthony Williams.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
]
[section:condvar_ref Condition Variables]
[heading Synopsis]
The classes `condition_variable` and `condition_variable_any` provide a
mechanism for one thread to wait for notification from another thread that a
particular condition has become true. The general usage pattern is that one
thread locks a mutex and then calls `wait` on an instance of
`condition_variable` or `condition_variable_any`. When the thread is woken from
the wait, then it checks to see if the appropriate condition is now true, and
continues if so. If the condition is not true, then the thread then calls `wait`
again to resume waiting. In the simplest case, this condition is just a boolean
variable:
boost::condition_variable cond;
boost::mutex mut;
bool data_ready;
void process_data();
void wait_for_data_to_process()
{
boost::unique_lock<boost::mutex> lock(mut);
while(!data_ready)
{
cond.wait(lock);
}
process_data();
}
Notice that the `lock` is passed to `wait`: `wait` will atomically add the
thread to the set of threads waiting on the condition variable, and unlock the
mutex. When the thread is woken, the mutex will be locked again before the call
to `wait` returns. This allows other threads to acquire the mutex in order to
update the shared data, and ensures that the data associated with the condition
is correctly synchronized.
In the mean time, another thread sets the condition to `true`, and then calls
either `notify_one` or `notify_all` on the condition variable to wake one
waiting thread or all the waiting threads respectively.
void retrieve_data();
void prepare_data();
void prepare_data_for_processing()
{
retrieve_data();
prepare_data();
{
boost::lock_guard<boost::mutex> lock(mut);
data_ready=true;
}
cond.notify_one();
}
Note that the same mutex is locked before the shared data is updated, but that
the mutex does not have to be locked across the call to `notify_one`.
This example uses an object of type `condition_variable`, but would work just as
well with an object of type `condition_variable_any`: `condition_variable_any`
is more general, and will work with any kind of lock or mutex, whereas
`condition_variable` requires that the lock passed to `wait` is an instance of
`boost::unique_lock<boost::mutex>`. This enables `condition_variable` to make
optimizations in some cases, based on the knowledge of the mutex type;
`condition_variable_any` typically has a more complex implementation than
`condition_variable`.
[section:condition_variable Class `condition_variable`]
#include <boost/thread/condition_variable.hpp>
namespace boost
{
class condition_variable
{
public:
condition_variable();
~condition_variable();
void notify_one();
void notify_all();
void wait(boost::unique_lock<boost::mutex>& lock);
template<typename predicate_type>
void wait(boost::unique_lock<boost::mutex>& lock,predicate_type predicate);
bool timed_wait(boost::unique_lock<boost::mutex>& lock,boost::system_time const& abs_time);
template<typename duration_type>
bool timed_wait(boost::unique_lock<boost::mutex>& lock,duration_type const& rel_time);
template<typename predicate_type>
bool timed_wait(boost::unique_lock<boost::mutex>& lock,boost::system_time const& abs_time,predicate_type predicate);
template<typename duration_type,typename predicate_type>
bool timed_wait(boost::unique_lock<boost::mutex>& lock,duration_type const& rel_time,predicate_type predicate);
// backwards compatibility
bool timed_wait(boost::unique_lock<boost::mutex>& lock,boost::xtime const& abs_time);
template<typename predicate_type>
bool timed_wait(boost::unique_lock<boost::mutex>& lock,boost::xtime const& abs_time,predicate_type predicate);
};
}
[section:constructor `condition_variable()`]
[variablelist
[[Effects:] [Constructs an object of class `condition_variable`.]]
[[Throws:] [__thread_resource_error__ if an error occurs.]]
]
[endsect]
[section:destructor `~condition_variable()`]
[variablelist
[[Precondition:] [All threads waiting on `*this` have been notified by a call to
`notify_one` or `notify_all` (though the respective calls to `wait` or
`timed_wait` need not have returned).]]
[[Effects:] [Destroys the object.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:notify_one `void notify_one()`]
[variablelist
[[Effects:] [If any threads are currently __blocked__ waiting on `*this` in a call
to `wait` or `timed_wait`, unblocks one of those threads.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:notify_all `void notify_all()`]
[variablelist
[[Effects:] [If any threads are currently __blocked__ waiting on `*this` in a call
to `wait` or `timed_wait`, unblocks all of those threads.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:wait `void wait(boost::unique_lock<boost::mutex>& lock)`]
[variablelist
[[Precondition:] [`lock` is locked by the current thread, and either no other
thread is currently waiting on `*this`, or the execution of the `mutex()` member
function on the `lock` objects supplied in the calls to `wait` or `timed_wait`
in all the threads currently waiting on `*this` would return the same value as
`lock->mutex()` for this call to `wait`.]]
[[Effects:] [Atomically call `lock.unlock()` and blocks the current thread. The
thread will unblock when notified by a call to `this->notify_one()` or
`this->notify_all()`, or spuriously. When the thread is unblocked (for whatever
reason), the lock is reacquired by invoking `lock.lock()` before the call to
`wait` returns. The lock is also reacquired by invoking `lock.lock()` if the
function exits with an exception.]]
[[Postcondition:] [`lock` is locked by the current thread.]]
[[Throws:] [__thread_resource_error__ if an error
occurs. __thread_interrupted__ if the wait was interrupted by a call to
__interrupt__ on the __thread__ object associated with the current thread of execution.]]
]
[endsect]
[section:wait_predicate `template<typename predicate_type> void wait(boost::unique_lock<boost::mutex>& lock, predicate_type pred)`]
[variablelist
[[Effects:] [As-if ``
while(!pred())
{
wait(lock);
}
``]]
]
[endsect]
[section:timed_wait `bool timed_wait(boost::unique_lock<boost::mutex>& lock,boost::system_time const& abs_time)`]
[variablelist
[[Precondition:] [`lock` is locked by the current thread, and either no other
thread is currently waiting on `*this`, or the execution of the `mutex()` member
function on the `lock` objects supplied in the calls to `wait` or `timed_wait`
in all the threads currently waiting on `*this` would return the same value as
`lock->mutex()` for this call to `wait`.]]
[[Effects:] [Atomically call `lock.unlock()` and blocks the current thread. The
thread will unblock when notified by a call to `this->notify_one()` or
`this->notify_all()`, when the time as reported by `boost::get_system_time()`
would be equal to or later than the specified `abs_time`, or spuriously. When
the thread is unblocked (for whatever reason), the lock is reacquired by
invoking `lock.lock()` before the call to `wait` returns. The lock is also
reacquired by invoking `lock.lock()` if the function exits with an exception.]]
[[Returns:] [`false` if the call is returning because the time specified by
`abs_time` was reached, `true` otherwise.]]
[[Postcondition:] [`lock` is locked by the current thread.]]
[[Throws:] [__thread_resource_error__ if an error
occurs. __thread_interrupted__ if the wait was interrupted by a call to
__interrupt__ on the __thread__ object associated with the current thread of execution.]]
]
[endsect]
[section:timed_wait_rel `template<typename duration_type> bool timed_wait(boost::unique_lock<boost::mutex>& lock,duration_type const& rel_time)`]
[variablelist
[[Precondition:] [`lock` is locked by the current thread, and either no other
thread is currently waiting on `*this`, or the execution of the `mutex()` member
function on the `lock` objects supplied in the calls to `wait` or `timed_wait`
in all the threads currently waiting on `*this` would return the same value as
`lock->mutex()` for this call to `wait`.]]
[[Effects:] [Atomically call `lock.unlock()` and blocks the current thread. The
thread will unblock when notified by a call to `this->notify_one()` or
`this->notify_all()`, after the period of time indicated by the `rel_time`
argument has elapsed, or spuriously. When the thread is unblocked (for whatever
reason), the lock is reacquired by invoking `lock.lock()` before the call to
`wait` returns. The lock is also reacquired by invoking `lock.lock()` if the
function exits with an exception.]]
[[Returns:] [`false` if the call is returning because the time period specified
by `rel_time` has elapsed, `true` otherwise.]]
[[Postcondition:] [`lock` is locked by the current thread.]]
[[Throws:] [__thread_resource_error__ if an error
occurs. __thread_interrupted__ if the wait was interrupted by a call to
__interrupt__ on the __thread__ object associated with the current thread of execution.]]
]
[note The duration overload of timed_wait is difficult to use correctly. The overload taking a predicate should be preferred in most cases.]
[endsect]
[section:timed_wait_predicate `template<typename predicate_type> bool timed_wait(boost::unique_lock<boost::mutex>& lock, boost::system_time const& abs_time, predicate_type pred)`]
[variablelist
[[Effects:] [As-if ``
while(!pred())
{
if(!timed_wait(lock,abs_time))
{
return pred();
}
}
return true;
``]]
]
[endsect]
[endsect]
[section:condition_variable_any Class `condition_variable_any`]
#include <boost/thread/condition_variable.hpp>
namespace boost
{
class condition_variable_any
{
public:
condition_variable_any();
~condition_variable_any();
void notify_one();
void notify_all();
template<typename lock_type>
void wait(lock_type& lock);
template<typename lock_type,typename predicate_type>
void wait(lock_type& lock,predicate_type predicate);
template<typename lock_type>
bool timed_wait(lock_type& lock,boost::system_time const& abs_time);
template<typename lock_type,typename duration_type>
bool timed_wait(lock_type& lock,duration_type const& rel_time);
template<typename lock_type,typename predicate_type>
bool timed_wait(lock_type& lock,boost::system_time const& abs_time,predicate_type predicate);
template<typename lock_type,typename duration_type,typename predicate_type>
bool timed_wait(lock_type& lock,duration_type const& rel_time,predicate_type predicate);
// backwards compatibility
template<typename lock_type>
bool timed_wait(lock_type>& lock,boost::xtime const& abs_time);
template<typename lock_type,typename predicate_type>
bool timed_wait(lock_type& lock,boost::xtime const& abs_time,predicate_type predicate);
};
}
[section:constructor `condition_variable_any()`]
[variablelist
[[Effects:] [Constructs an object of class `condition_variable_any`.]]
[[Throws:] [__thread_resource_error__ if an error occurs.]]
]
[endsect]
[section:destructor `~condition_variable_any()`]
[variablelist
[[Precondition:] [All threads waiting on `*this` have been notified by a call to
`notify_one` or `notify_all` (though the respective calls to `wait` or
`timed_wait` need not have returned).]]
[[Effects:] [Destroys the object.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:notify_one `void notify_one()`]
[variablelist
[[Effects:] [If any threads are currently __blocked__ waiting on `*this` in a call
to `wait` or `timed_wait`, unblocks one of those threads.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:notify_all `void notify_all()`]
[variablelist
[[Effects:] [If any threads are currently __blocked__ waiting on `*this` in a call
to `wait` or `timed_wait`, unblocks all of those threads.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:wait `template<typename lock_type> void wait(lock_type& lock)`]
[variablelist
[[Effects:] [Atomically call `lock.unlock()` and blocks the current thread. The
thread will unblock when notified by a call to `this->notify_one()` or
`this->notify_all()`, or spuriously. When the thread is unblocked (for whatever
reason), the lock is reacquired by invoking `lock.lock()` before the call to
`wait` returns. The lock is also reacquired by invoking `lock.lock()` if the
function exits with an exception.]]
[[Postcondition:] [`lock` is locked by the current thread.]]
[[Throws:] [__thread_resource_error__ if an error
occurs. __thread_interrupted__ if the wait was interrupted by a call to
__interrupt__ on the __thread__ object associated with the current thread of execution.]]
]
[endsect]
[section:wait_predicate `template<typename lock_type,typename predicate_type> void wait(lock_type& lock, predicate_type pred)`]
[variablelist
[[Effects:] [As-if ``
while(!pred())
{
wait(lock);
}
``]]
]
[endsect]
[section:timed_wait `template<typename lock_type> bool timed_wait(lock_type& lock,boost::system_time const& abs_time)`]
[variablelist
[[Effects:] [Atomically call `lock.unlock()` and blocks the current thread. The
thread will unblock when notified by a call to `this->notify_one()` or
`this->notify_all()`, when the time as reported by `boost::get_system_time()`
would be equal to or later than the specified `abs_time`, or spuriously. When
the thread is unblocked (for whatever reason), the lock is reacquired by
invoking `lock.lock()` before the call to `wait` returns. The lock is also
reacquired by invoking `lock.lock()` if the function exits with an exception.]]
[[Returns:] [`false` if the call is returning because the time specified by
`abs_time` was reached, `true` otherwise.]]
[[Postcondition:] [`lock` is locked by the current thread.]]
[[Throws:] [__thread_resource_error__ if an error
occurs. __thread_interrupted__ if the wait was interrupted by a call to
__interrupt__ on the __thread__ object associated with the current thread of execution.]]
]
[endsect]
[section:timed_wait_rel `template<typename lock_type,typename duration_type> bool timed_wait(lock_type& lock,duration_type const& rel_time)`]
[variablelist
[[Effects:] [Atomically call `lock.unlock()` and blocks the current thread. The
thread will unblock when notified by a call to `this->notify_one()` or
`this->notify_all()`, after the period of time indicated by the `rel_time`
argument has elapsed, or spuriously. When the thread is unblocked (for whatever
reason), the lock is reacquired by invoking `lock.lock()` before the call to
`wait` returns. The lock is also reacquired by invoking `lock.lock()` if the
function exits with an exception.]]
[[Returns:] [`false` if the call is returning because the time period specified
by `rel_time` has elapsed, `true` otherwise.]]
[[Postcondition:] [`lock` is locked by the current thread.]]
[[Throws:] [__thread_resource_error__ if an error
occurs. __thread_interrupted__ if the wait was interrupted by a call to
__interrupt__ on the __thread__ object associated with the current thread of execution.]]
]
[note The duration overload of timed_wait is difficult to use correctly. The overload taking a predicate should be preferred in most cases.]
[endsect]
[section:timed_wait_predicate `template<typename lock_type,typename predicate_type> bool timed_wait(lock_type& lock, boost::system_time const& abs_time, predicate_type pred)`]
[variablelist
[[Effects:] [As-if ``
while(!pred())
{
if(!timed_wait(lock,abs_time))
{
return pred();
}
}
return true;
``]]
]
[endsect]
[endsect]
[section:condition Typedef `condition`]
#include <boost/thread/condition.hpp>
typedef condition_variable_any condition;
The typedef `condition` is provided for backwards compatibility with previous boost releases.
[endsect]
[endsect]

94
doc/configuration.html Normal file
View File

@@ -0,0 +1,94 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Configuration</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Configuration</h2>
</td>
</tr>
</table>
<hr>
<dl class="page-index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#lib-defined-public">Public Library Defined Macros</a></dt>
<dt><a href="#lib-defined-impl">Library Defined Implementation Macros</a></dt>
</dl>
<h2><a name="introduction"></a>Introduction</h2>
<p><b>Boost.Threads</b> uses several configuration macros in <a href="../../config/config.htm">&lt;boost/config.hpp&gt;</a>,
as well as configuration macros meant to be supplied by the application. These
macros are documented here.</p>
<h2><a name="lib-defined-public"></a>Public Library Defined Macros</h2>
<p>These macros are defined by <b>Boost.Threads</b> but are expected to be used
by application code.</p>
<table summary="public library defined macros" cellspacing="10" width="100%">
<tr>
<td><b>Macro</b></td>
<td><b>Meaning</b></td>
</tr>
<tr>
<td>BOOST_HAS_THREADS</td>
<td>Indicates that threading support is available. This means both that there
is a platform specific implementation for <b>Boost.Threads</b> and that
threading support has been enabled in a platform specific manner. For instance,
on the Win32 platform there&#39;s an implementation for <b>Boost.Threads</b>
but unless the program is compiled against one of the multithreading runtimes
(often determined by the compiler predefining the macro _MT) the BOOST_HAS_THREADS
macro remains undefined.</td>
</tr>
</table>
<h2><a name="lib-defined-impl"></a>Library Defined Implementation Macros</h2>
<p>These macros are defined by <b>Boost.Threads</b> and are implementation details
of interest only to implementors.</p>
<table summary="library defined implementation macros" cellspacing="10" width="100%">
<tr>
<td><b>Macro</b></td>
<td><b>Meaning</b></td>
</tr>
<tr>
<td>BOOST_HAS_WINTHREADS</td>
<td>Indicates that the platform has the Microsoft Win32 threading libraries,
and that they should be used to implement <b>Boost.Threads</b>.</td>
</tr>
<tr>
<td>BOOST_HAS_PTHREADS</td>
<td>Indicates that the platform has the POSIX pthreads libraries, and that
they should be used to implement <b>Boost.Threads</b>.</td>
</tr>
<tr>
<td>BOOST_HAS_FTIME</td>
<td>Indicates that the implementation should use GetSystemTimeAsFileTime()
and the FILETIME type to calculate the current time. This is an implementation
detail used by boost::detail::getcurtime().</td>
</tr>
<tr>
<td>BOOST_HAS_GETTTIMEOFDAY</td>
<td>Indicates that the implementation should use gettimeofday() to calculate
the current time. This is an implementation detail used by boost::detail::getcurtime().</td>
</tr>
</table>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

263
doc/definitions.html Normal file
View File

@@ -0,0 +1,263 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Definitions</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Definitions</h2>
</td>
</tr>
</table>
<hr>
<h2>Contents</h2>
<dl class="page-index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#definitions">Definitions</a></dt>
<dl class="page-index">
<dt><a href="#definition-thread">Thread</a></dt>
<dt><a href="#definition-thread-safe">Thread-safe</a></dt>
<dt><a href="#definition-thread-state">Thread State</a></dt>
<dt><a href="#definition-race-condition">Race Condition</a></dt>
<dt><a href="#definition-deadlock">Deadlock</a></dt>
<dt><a href="#definition-starvation">Starvation</a></dt>
<dt><a href="#definition-priority-failure">Priority Failure</a></dt>
<dt><a href="#definition-visibility">Memory Visibility</a></dt>
</dl>
<dt><a href="#acknowledgements">Acknowledgments</a></dt>
</dl>
<hr>
<h2><a name="introduction"></a>Introduction</h2>
<p>The definitions are given in terms of the <a href=
"bibliography.html#ISO-98">C++ Standard</a>. References to the standard
are in the form [1.2.3/4], which represents the section number, with the paragraph
number following the &quot;/&quot;.</p>
<p>Because the definitions are written in something akin to &quot;standardese&quot;,
they can be difficult to understand. The intent isn&#39;t to confuse, but rather
to clarify the additional requirements Boost.Threads places on a C++ implementation
as defined by the C++ Standard.</p>
<h2><a name="definitions"></a>Definitions</h2>
<h3><a name="definition-thread"></a>Thread</h3>
<p>Thread is short for &quot;thread of execution&quot;. A thread of execution
is an execution environment [1.9/7] within the execution environment of a C++
program [1.9]. The main() function [3.6.1] of the program is the initial function
of the initial thread. A program in a multithreading environment always has
an initial thread even if the program explicitly creates no additional threads.</p>
<p>Unless otherwise specified, each thread shares all aspects of its execution
environment with other threads in the program. Shared aspects of the execution
environment include, but are not limited to, the following:</p>
<ul>
<li>Static storage duration (static, extern) objects [3.7.1].</li>
</ul>
<ul>
<li>Dynamic storage duration (heap) objects [3.7.3]. Thus each memory allocation
will return a unique addresses, regardless of the thread making the allocation
request.</li>
</ul>
<ul>
<li>Automatic storage duration (stack) objects [3.7.2] accessed via pointer
or reference from another thread.</li>
</ul>
<ul>
<li>Resources provided by the operating system. For example, files.</li>
</ul>
<ul>
<li>The program itself. In other words, each thread is executing some function
of the same program, not a totally different program.</li>
</ul>
<p>Each thread has its own:</p>
<ul>
<li>Registers and current execution sequence (program counter) [1.9/5].</li>
</ul>
<ul>
<li>Automatic storage duration (stack) objects [3.7.2].</li>
</ul>
<h3><a name="definition-thread-safe"></a>Thread-safe</h3>
<p>A program is thread-safe if it has no <a href="#Race condition">race conditions</a>,
does not <a href="#Deadlock">deadlock</a>, and has no <a href="#Priority failure">priority
failures</a>.</p>
<p>Note that thread-safety does not necessarily imply efficiency, and than while
some thread-safety violations can be determined statically at compile time,
many thread-safety errors can only only be detected at runtime.</p>
<h3><a name="definition-thread-state"></a>Thread State</h3>
<p>During the lifetime of a thread, it shall be in one of the following states:</p>
<table summary="thread states" border="1" cellpadding="5">
<tr>
<td><b>State</b></td>
<td><b>Description</b></td>
</tr>
<tr>
<td>Ready</td>
<td>Ready to run, but waiting for a processor.</td>
</tr>
<tr>
<td>Running</td>
<td>Currently executing on a processor. Zero or more threads may be running
at any time, with a maximum equal to the number of processors.</td>
</tr>
<tr>
<td>Blocked</td>
<td>Waiting for some resource other than a processor which is not currently
available, or for the completion of calls to library functions [1.9/6].
The term &quot;waiting&quot; is synonymous for &quot;blocked&quot;</td>
</tr>
<tr>
<td>Terminated</td>
<td>Finished execution but not yet detached or joined.</td>
</tr>
</table>
<p>Thread state transitions shall occur only as specified:</p>
<table summary="state transitions" border="1" cellpadding="5">
<tr>
<td><b>From</b></td>
<td><b>To</b></td>
<td><b>Cause</b></td>
</tr>
<tr>
<td>
<p align="left">[none]</p>
</td>
<td>Ready</td>
<td>Thread is created by a call to a library function. In the case of the
initial thread, creation is implicit and occurs during the startup of the
main() function [3.6.1].</td>
</tr>
<tr>
<td>Ready</td>
<td>Running</td>
<td>Processor becomes available.</td>
</tr>
<tr>
<td>Running</td>
<td>Ready</td>
<td>Thread preempted.</td>
</tr>
<tr>
<td>Running</td>
<td>Blocked</td>
<td>Thread calls a library function which waits for a resource or for the
completion of I/O.</td>
</tr>
<tr>
<td>Running</td>
<td>Terminated</td>
<td>Thread returns from its initial function, calls a thread termination library
function, or is canceled by some other thread calling a thread termination
library function.</td>
</tr>
<tr>
<td>Blocked</td>
<td>Ready</td>
<td>The resource being waited for becomes available, or the blocking library
function completes.</td>
</tr>
<tr>
<td>Terminated</td>
<td>[none]</td>
<td>Thread is detached or joined by some other thread calling the appropriate
library function, or by program termination [3.6.3].</td>
</tr>
</table>
<p>[Note: if a suspend() function is added to the threading library, additional
transitions to the blocked state will have to be added to the above table.]</p>
<h3><a name="definition-race-condition"></a>Race Condition</h3>
<p>A race condition is what occurs when multiple threads read and write to the
same memory without proper synchronization, resulting in an incorrect value
being read or written. The result of a race condition may be a bit pattern which
isn&#39;t even a valid value for the data type. A race condition results in
undefined behavior [1.3.12].</p>
<p>Race conditions can be prevented by serializing memory access using the tools
provided by Boost.Threads.</p>
<h3><a name="definition-deadlock"></a>Deadlock</h3>
<p>Deadlock is an execution state where for some set of threads, each thread in
the set is blocked waiting for some action by one of the other threads in the
set. Since each is waiting on the others, none will ever become ready again.</p>
<h3><a name="definition-starvation"></a>Starvation</h3>
<p>The condition in which a thread is not making sufficient progress in its work
during a given time interval.</p>
<h3><a name="definition-priority-failure"></a>Priority Failure</h3>
<p>A priority failure (such as priority inversion or infinite overtaking) occurs
when threads executed in such a sequence that required work is not performed
in time to be useful.</p>
<h3><a name="definition-visibility"></a>Memory Visibility</h3>
<p>An address [1.7] shall always point to the same memory byte, regardless of
the thread or processor dereferencing the address.</p>
<p>An object [1.8, 1.9] is accessible from multiple threads if it is of static
storage duration (static, extern) [3.7.1], or if a pointer or reference to it
is explicitly or implicitly dereferenced in multiple threads.</p>
<p>For an object accessible from multiple threads, the value of the object accessed
from one thread may be indeterminate or different than the value accessed from
another thread, except under the conditions specified in the following table.
For the same row of the table, the value of an object accessible at the indicated
sequence point in thread A will be determinate and the same if accessed at or
after the indicated sequence point in thread B, provided the object is not otherwise
modified. In the table, the &quot;sequence point at a call&quot; is the sequence
point after the evaluation of all function arguments [1.9/17], while the &quot;sequence
point after a call&quot; is the sequence point after the copying of the returned
value...&quot; [1.9/17].</p>
<table summary="memory visibility" border="1" cellpadding="5">
<tr>
<td align="center"><b>Thread A</b></td>
<td align="center"><b>Thread B</b></td>
</tr>
<tr>
<td>The sequence point at a call to a library thread-creation function.</td>
<td>The first sequence point of the initial function in the new thread created
by the Thread A call.</td>
</tr>
<tr>
<td>The sequence point at a call to a library function which locks a mutex,
directly or by waiting for a condition variable.</td>
<td>The sequence point after a call to a library function which unlocks the
same mutex.</td>
</tr>
<tr>
<td>The last sequence point before thread termination.</td>
<td>The sequence point after a call to a library function which joins the
terminated thread.</td>
</tr>
<tr>
<td>The sequence point at a call to a library function which signals or broadcasts
a condition variable.</td>
<td>The sequence point after the call to the library function which was waiting
on that same condition variable or signal.</td>
</tr>
</table>
<p>The architecture of the execution environment and the observable behavior of
the abstract machine [1.9] shall be the same on all processors.</p>
<p>The latitude granted by the C++ standard for an implementation to alter the
definition of observable behavior of the abstract machine to include additional
library I/O functions [1.9/6] is extended to include threading library functions.</p>
<p>When an exception is thrown and there is no matching exception handler in the
same thread, behavior is undefined. The preferred behavior is the same as when
there is no matching exception handler in a program [15.3/9]. That is, terminate()
is called, and it is implementation defined whether or not the stack is unwound.</p>
<h2><a name="acknowledgements"></a>Acknowledgments</h2>
<p>This document has been much improved by the incorporation of comments from
William Kempf.</p>
<p>The visibility rules are based on <a href=
"bibliography.html#Butenhof-97">[Butenhof 97]</a>.</p>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

110
doc/exceptions.html Normal file
View File

@@ -0,0 +1,110 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Header &lt;boost/thread/exceptions.hpp&gt;</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Header &lt;<a href="../../../boost/thread/exceptions.hpp">boost/thread/exceptions.hpp</a>&gt;</h2>
</td>
</tr>
</table>
<hr>
<h2>Contents</h2>
<dl class="page-index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#classes">Classes</a></dt>
<dl class="page-index">
<dt><a href="#class-lock_error">Class <code>lock_error</code></a></dt>
<dl class="page-index">
<dt><a href="#class-lock_error-synopsis">Class <code>lock_error</code> synopsis</a></dt>
<dt><a href="#class-lock_error-ctors">Class <code>lock_error</code> constructors
and destructor</a></dt>
</dl>
<dt><a href="#class-thread_resource_error">Class <code>thread_resource_error</code></a></dt>
<dl class="page-index">
<dt><a href="#class-thread_resource_error-synopsis">Class <code>thread_resource_error</code>
synopsis</a></dt>
<dt><a href="#class-thread_resource_error-ctors">Class <code>thread_resource_error</code>
constructors and destructor</a></dt>
</dl>
</dl>
</dl>
<hr>
<h2><a name="introduction"></a>Introduction</h2>
<p>Include the header &lt;<a href="../../../boost/thread/exceptions.hpp">boost/thread/exceptions.hpp</a>&gt;
to define the exception types that may be thrown by <b>Boost.Threads</b> classes.</p>
<h2><a name="classes"></a>Classes</h2>
<h3><a name="class-lock_error"></a>Class <code>lock_error</code></h3>
<p>The lock_error class defines an exception type thrown to indicate a locking
related error has been detected. Examples of such errors include a lock operation
which can be determined to result in a deadlock, or unlock operations attempted
by a thread that does not own the lock. </p>
<h4><a name="class-lock_error-synopsis"></a>Class <code>lock_error</code> synopsis</h4>
<pre>
namespace boost
{
class lock_error : public std::logical_error
{
public:
lock_error();
};
};
</pre>
<h4><a name="class-lock_error-ctors"></a>Class <code>lock_error</code> constructors
and destructor</h4>
<pre>
lock_error();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Constructs a <code>lock_error</code> object.</dt>
</dl>
<h3><a name="class-thread_resource_error"></a>Class <code>thread_resource_error</code></h3>
<p>The thread_resource_error class defines an exception type that is thrown by
constructors in the Boost.Threads library when thread related resources can
not be acquired. This does not include memory allocation failures which instead
throw std::bad_alloc. </p>
<h4><a name="class-thread_resource_error-synopsis"></a>Class <code>thread_resource_error</code>
synopsis</h4>
<pre>
namespace boost
{
class thread_resource_error : public std::runtime_error
{
public:
thread_resource_error();
};
};
</pre>
<h4><a name="class-thread_resource_error-ctors"></a>Class <code>thread_resource_error</code>
constructors and destructor</h4>
<pre>
thread_resource_error();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Constructs a <code>thread_resource_error</code> object.</dt>
</dl>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

183
doc/faq.html Normal file
View File

@@ -0,0 +1,183 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - FAQ</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Frequently Asked Questions (FAQs)</h2>
</td>
</tr>
</table>
<hr>
<dl class="page-index">
<dt><a href="#question1">1. Are lock objects thread safe?</a></dt>
<dt><a href="#question2a">2a. Why was <b>Boost.Threads</b> modeled after (specific
library name)?</a></dt>
<dt><a href="#question2b">2b. Why wasn't <b>Boost.Threads</b> modeled after
(specific library name)?</a></dt>
<dt><a href="#question3">3. Why do mutexes have noncopyable semantics?</a></dt>
<dt><a href="#question4">4. How can you prevent deadlock from occurring when
a thread must lock multiple mutexes?</a></dt>
<dt><a href="#question5">5. Don't noncopyable mutex semantics mean that a class
with a mutex member will be noncopyable as well?</a></dt>
<dt><a href="#question6">6. How can you lock a mutex member in a const member
function (in order to implement the monitor pattern)?</a></dt>
<dt><a href="#question7">7. Why supply condition variables rather than event
variables?</a></dt>
<dt><a href="#question8">8. Why isn't thread cancellation or termination provided?</a></dt>
<dt><a href="#question9">9. Is it safe for threads to share automatic storage
duration (stack) objects via pointers or references?</a></dt>
<dt><a href="#question10">10. Why has class semaphore disappeared?</a></dt>
</dl>
<h2><a name="question1"></a>1. Are lock objects <a href="definitions.html#definition-thread-safe">
thread safe</a>?</h2>
<p><b>No!</b> Lock objects are not meant to be shared between threads. They are
meant to be short-lived objects created on automatic storage within a code block.
Any other usage is just likely to lead to errors and won&#39;t really be of
actual benefit any way. Share <a href=
"mutex_concept.html">mutexes</a>, not locks. For more information see
the <a href="rationale.html#lock_objects">rationale</a> behind the design for
lock objects.</p>
<h2><a name="question2a"></a>2a. Why was <b>Boost.Threads</b> modeled after (specific
library name)?</h2>
<p>It wasn&#39;t. Boost.Threads was designed from scratch. Extensive design discussions
involved numerous people representing a wide range of experience across many
platforms. To ensure portability, the initial implements were done in parallel
using POSIX Threads and the Win32 threading API. But the Boost.Threads design
is very much in the spirit of C++, and thus doesn&#39;t model such C based APIs.</p>
<h2><a name="question2b"></a>2b. Why wasn&#39;t Boost.Threads modeled after (specific
library name)?</h2>
<p>Existing C++ libraries either seemed dangerous (often failing to take advantage
of prior art to reduce errors) or had excessive dependencies on library components
unrelated to threading. Existing C libraries couldn&#39;t meet our C++ requirements,
and were also missing certain features. For instance, the WIN32 thread API lacks
condition variables, even though these are critical for the important Monitor
pattern <a href="bibliography.html#Schmidt-00">[Schmidt 00]</a>.</p>
<h2><a name="question3"></a>3. Why do <a href="mutex_concept.html">Mutexes</a>
have noncopyable semantics?</h2>
<p>To ensure that <a href="definitions.html#Deadlock">deadlocks</a> don&#39;t
occur. The only logical form of copy would be to use some sort of shallow copy
semantics in which multiple mutex objects could refer to the same mutex state.
This means that if ObjA has a mutex object as part of its state and ObjB is
copy constructed from it, then when ObjB::foo() locks the mutex it has effectively
locked ObjA as well. This behavior can result in deadlock. Other copy semantics
result in similar problems (if you think you can prove this to be wrong then
supply us with an alternative and we&#39;ll reconsider).</p>
<h2><a name="question4"></a>4. How can you prevent <a href="definitions.html#Deadlock">
deadlock</a> from occurring when a thread must lock multiple mutexes?</h2>
<p>Always lock them in the same order. One easy way of doing this is to use each
mutex&#39;s address to determine the order in which they are locked. A future
Boost.Threads concept may wrap this pattern up in a reusable class.</p>
<h2><a name="question5"></a>5. Don&#39;t noncopyable <a href="mutex_concept.html">mutex</a>
semantics mean that a class with a mutex member will be noncopyable as well?</h2>
<p>No, but what it does mean is that the compiler can&#39;t generate a copy constructor
and assignment operator, so they will have to be coded explicitly. This is a
<b>good thing</b>, however, since the compiler generated operations would not
be <a href=
"definitions.html#Thread-safe">thread-safe</a>. The following is a simple
example of a class with copyable semantics and internal synchronization through
a mutex member.</p>
<pre>
class counter
{
public:
// Doesn't need synchronization since there can be no references to *this
// until after it's constructed!
explicit counter(int initial_value)
: m_value(initial_value)
{
}
// We only need to synchronize other for the same reason we don't have to
// synchronize on construction!
counter(const counter&amp; other)
{
boost::mutex::scoped_lock scoped_lock(other.m_mutex);
m_value = other.m_value;
}
// For assignment we need to synchronize both objects!
const counter&amp; operator=(const counter&amp; other)
{
if (this == &amp;other)
return *this;
boost::mutex::scoped_lock lock1(&amp;m_mutex &lt; &amp;other.m_mutex ? m_mutex : other.m_mutex);
boost::mutex::scoped_lock lock2(&amp;m_mutex &gt; &amp;other.m_mutex ? m_mutex : other.m_mutex);
m_value = other.m_value;
return *this;
}
int value() const
{
boost::mutex::scoped_lock scoped_lock(m_mutex);
return m_value;
}
int increment()
{
boost::mutex::scoped_lock scoped_lock(m_mutex);
return ++m_value;
}
private:
mutable boost::mutex m_mutex;
int m_value;
};
</pre>
<h2><a name="question6"></a>6. How can you lock a <a href="mutex_concept.html">mutex</a>
member in a const member function, in order to implement the Monitor Pattern?</h2>
<p>The Monitor Pattern mutex <a href="bibliography.html#Schmidt-00"> [Schmidt
00]</a> should simply be declared as mutable. See the example code above. The
internal state of mutex types could have been made mutable, with all lock calls
made via const functions, but this does a poor job of documenting the actual
semantics (and in fact would be incorrect since the logical state of a locked
mutex clearly differs from the logical state of an unlocked mutex). Declaring
a mutex member as mutable clearly documents the intended semantics.</p>
<h2><a name="question7"></a>7. Why supply <a href="condition.html">condition variables</a>
rather than <a href="rationale.html#Events">event variables</a>?</h2>
<p>Condition variables result in user code much less prone to <a href=
"definitions.html#Race condition">race conditions</a> than event variables.
See <a href="rationale.html#Events">Rationale</a> for analysis. Also see <a href="bibliography.html#Hoare-74">[Hoare
74]</a> and <a href="bibliography.html#Schmidt-00">[Schmidt 00]</a>.</p>
<h2><a name="question8"></a>8. Why isn&#39;t thread cancellation or termination
provided?</h2>
<p>There&#39;s a valid need for thread termination, so at some point Boost.Threads
probably will include it, but only after we can find a truly safe (and portable)
mechanism for this concept.</p>
<h2><a name="question9"></a>9. Is it safe for threads to share automatic storage
duration (stack) objects via pointers or references?</h2>
<p>Only if you can guarantee that the lifetime of the stack object will not end
while other threads might still access the object. Thus the safest practice
is to avoid sharing stack objects, particularly in designs where threads are
created and destroyed dynamically. Restrict sharing of stack objects to simple
designs with very clear and unchanging function and thread lifetimes. (Suggested
by Darryl Green).</p>
<h2><a name="question10"></a>10. Why has class semaphore disappeared?</h2>
<p>Semaphore was removed as too error prone. The same effect can be achieved with
greater safety by the combination of a mutex and a condition variable.</p>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

View File

@@ -1,968 +0,0 @@
[/
(C) Copyright 2008-9 Anthony Williams.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
]
[section:reference Futures Reference]
[section:future_state `state` enum]
namespace future_state
{
enum state {uninitialized, waiting, ready};
}
[endsect]
[section:unique_future `unique_future` class template]
template <typename R>
class unique_future
{
unique_future(unique_future & rhs);// = delete;
unique_future& operator=(unique_future& rhs);// = delete;
public:
typedef future_state::state state;
unique_future();
~unique_future();
// move support
unique_future(unique_future && other);
unique_future& operator=(unique_future && other);
void swap(unique_future& other);
// retrieving the value
R&& get();
// functions to check state
state get_state() const;
bool is_ready() const;
bool has_exception() const;
bool has_value() const;
// waiting for the result to be ready
void wait() const;
template<typename Duration>
bool timed_wait(Duration const& rel_time) const;
bool timed_wait_until(boost::system_time const& abs_time) const;
};
[section:default_constructor Default Constructor]
unique_future();
[variablelist
[[Effects:] [Constructs an uninitialized future.]]
[[Postconditions:] [[unique_future_is_ready_link `this->is_ready`] returns `false`. [unique_future_get_state_link
`this->get_state()`] returns __uninitialized__.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:destructor Destructor]
~unique_future();
[variablelist
[[Effects:] [Destroys `*this`.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:move_constructor Move Constructor]
unique_future(unique_future && other);
[variablelist
[[Effects:] [Constructs a new future, and transfers ownership of the asynchronous result associated with `other` to `*this`.]]
[[Postconditions:] [[unique_future_get_state_link `this->get_state()`] returns the value of `other->get_state()` prior to the
call. `other->get_state()` returns __uninitialized__. If `other` was associated with an asynchronous result, that result is now
associated with `*this`. `other` is not associated with any asynchronous result.]]
[[Throws:] [Nothing.]]
[[Notes:] [If the compiler does not support rvalue-references, this is implemented using the boost.thread move emulation.]]
]
[endsect]
[section:move_assignment Move Assignment Operator]
unique_future& operator=(unique_future && other);
[variablelist
[[Effects:] [Transfers ownership of the asynchronous result associated with `other` to `*this`.]]
[[Postconditions:] [[unique_future_get_state_link `this->get_state()`] returns the value of `other->get_state()` prior to the
call. `other->get_state()` returns __uninitialized__. If `other` was associated with an asynchronous result, that result is now
associated with `*this`. `other` is not associated with any asynchronous result. If `*this` was associated with an asynchronous
result prior to the call, that result no longer has an associated __unique_future__ instance.]]
[[Throws:] [Nothing.]]
[[Notes:] [If the compiler does not support rvalue-references, this is implemented using the boost.thread move emulation.]]
]
[endsect]
[section:swap Member function `swap()`]
void swap(unique_future & other);
[variablelist
[[Effects:] [Swaps ownership of the asynchronous results associated with `other` and `*this`.]]
[[Postconditions:] [[unique_future_get_state_link `this->get_state()`] returns the value of `other->get_state()` prior to the
call. `other->get_state()` returns the value of `this->get_state()` prior to the call. If `other` was associated with an
asynchronous result, that result is now associated with `*this`, otherwise `*this` has no associated result. If `*this` was
associated with an asynchronous result, that result is now associated with `other`, otherwise `other` has no associated result.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:get Member function `get()`]
R&& get();
R& unique_future<R&>::get();
void unique_future<void>::get();
[variablelist
[[Effects:] [If `*this` is associated with an asynchronous result, waits until the result is ready as-if by a call to
__unique_future_wait__, and retrieves the result (whether that is a value or an exception).]]
[[Returns:] [If the result type `R` is a reference, returns the stored reference. If `R` is `void`, there is no return
value. Otherwise, returns an rvalue-reference to the value stored in the asynchronous result.]]
[[Postconditions:] [[unique_future_is_ready_link `this->is_ready()`] returns `true`. [unique_future_get_state_link
`this->get_state()`] returns __ready__.]]
[[Throws:] [__future_uninitialized__ if `*this` is not associated with an asynchronous result. __thread_interrupted__ if the result
associated with `*this` is not ready at the point of the call, and the current thread is interrupted. Any exception stored in the
asynchronous result in place of a value.]]
[[Notes:] [`get()` is an ['interruption point].]]
]
[endsect]
[section:wait Member function `wait()`]
void wait();
[variablelist
[[Effects:] [If `*this` is associated with an asynchronous result, waits until the result is ready. If the result is not ready on
entry, and the result has a ['wait callback] set, that callback is invoked prior to waiting.]]
[[Throws:] [__future_uninitialized__ if `*this` is not associated with an asynchronous result. __thread_interrupted__ if the result
associated with `*this` is not ready at the point of the call, and the current thread is interrupted. Any exception thrown by the
['wait callback] if such a callback is called.]]
[[Postconditions:] [[unique_future_is_ready_link `this->is_ready()`] returns `true`. [unique_future_get_state_link
`this->get_state()`] returns __ready__.]]
[[Notes:] [`wait()` is an ['interruption point].]]
]
[endsect]
[section:timed_wait_duration Member function `timed_wait()`]
template<typename Duration>
bool timed_wait(Duration const& wait_duration);
[variablelist
[[Effects:] [If `*this` is associated with an asynchronous result, waits until the result is ready, or the time specified by
`wait_duration` has elapsed. If the result is not ready on entry, and the result has a ['wait callback] set, that callback is
invoked prior to waiting.]]
[[Returns:] [`true` if `*this` is associated with an asynchronous result, and that result is ready before the specified time has
elapsed, `false` otherwise.]]
[[Throws:] [__future_uninitialized__ if `*this` is not associated with an asynchronous result. __thread_interrupted__ if the result
associated with `*this` is not ready at the point of the call, and the current thread is interrupted. Any exception thrown by the
['wait callback] if such a callback is called.]]
[[Postconditions:] [If this call returned `true`, then [unique_future_is_ready_link `this->is_ready()`] returns `true` and
[unique_future_get_state_link `this->get_state()`] returns __ready__.]]
[[Notes:] [`timed_wait()` is an ['interruption point]. `Duration` must be a type that meets the Boost.DateTime time duration requirements.]]
]
[endsect]
[section:timed_wait_absolute Member function `timed_wait()`]
bool timed_wait(boost::system_time const& wait_timeout);
[variablelist
[[Effects:] [If `*this` is associated with an asynchronous result, waits until the result is ready, or the time point specified by
`wait_timeout` has passed. If the result is not ready on entry, and the result has a ['wait callback] set, that callback is invoked
prior to waiting.]]
[[Returns:] [`true` if `*this` is associated with an asynchronous result, and that result is ready before the specified time has
passed, `false` otherwise.]]
[[Throws:] [__future_uninitialized__ if `*this` is not associated with an asynchronous result. __thread_interrupted__ if the result
associated with `*this` is not ready at the point of the call, and the current thread is interrupted. Any exception thrown by the
['wait callback] if such a callback is called.]]
[[Postconditions:] [If this call returned `true`, then [unique_future_is_ready_link `this->is_ready()`] returns `true` and
[unique_future_get_state_link `this->get_state()`] returns __ready__.]]
[[Notes:] [`timed_wait()` is an ['interruption point].]]
]
[endsect]
[section:is_ready Member function `is_ready()`]
bool is_ready();
[variablelist
[[Effects:] [Checks to see if the asynchronous result associated with `*this` is set.]]
[[Returns:] [`true` if `*this` is associated with an asynchronous result, and that result is ready for retrieval, `false`
otherwise.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:has_value Member function `has_value()`]
bool has_value();
[variablelist
[[Effects:] [Checks to see if the asynchronous result associated with `*this` is set with a value rather than an exception.]]
[[Returns:] [`true` if `*this` is associated with an asynchronous result, that result is ready for retrieval, and the result is a
stored value, `false` otherwise.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:has_exception Member function `has_exception()`]
bool has_exception();
[variablelist
[[Effects:] [Checks to see if the asynchronous result associated with `*this` is set with an exception rather than a value.]]
[[Returns:] [`true` if `*this` is associated with an asynchronous result, that result is ready for retrieval, and the result is a
stored exception, `false` otherwise.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:get_state Member function `get_state()`]
future_state::state get_state();
[variablelist
[[Effects:] [Determine the state of the asynchronous result associated with `*this`, if any.]]
[[Returns:] [__uninitialized__ if `*this` is not associated with an asynchronous result. __ready__ if the asynchronous result
associated with `*this` is ready for retrieval, __waiting__ otherwise.]]
[[Throws:] [Nothing.]]
]
[endsect]
[endsect]
[section:shared_future `shared_future` class template]
template <typename R>
class shared_future
{
public:
typedef future_state::state state;
shared_future();
~shared_future();
// copy support
shared_future(shared_future const& other);
shared_future& operator=(shared_future const& other);
// move support
shared_future(shared_future && other);
shared_future(unique_future<R> && other);
shared_future& operator=(shared_future && other);
shared_future& operator=(unique_future<R> && other);
void swap(shared_future& other);
// retrieving the value
R get();
// functions to check state, and wait for ready
state get_state() const;
bool is_ready() const;
bool has_exception() const;
bool has_value() const;
// waiting for the result to be ready
void wait() const;
template<typename Duration>
bool timed_wait(Duration const& rel_time) const;
bool timed_wait_until(boost::system_time const& abs_time) const;
};
[section:default_constructor Default Constructor]
shared_future();
[variablelist
[[Effects:] [Constructs an uninitialized future.]]
[[Postconditions:] [[shared_future_is_ready_link `this->is_ready`] returns `false`. [shared_future_get_state_link
`this->get_state()`] returns __uninitialized__.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:get Member function `get()`]
const R& get();
[variablelist
[[Effects:] [If `*this` is associated with an asynchronous result, waits until the result is ready as-if by a call to
__shared_future_wait__, and returns a `const` reference to the result.]]
[[Returns:] [If the result type `R` is a reference, returns the stored reference. If `R` is `void`, there is no return
value. Otherwise, returns a `const` reference to the value stored in the asynchronous result.]]
[[Throws:] [__future_uninitialized__ if `*this` is not associated with an asynchronous result. __thread_interrupted__ if the
result associated with `*this` is not ready at the point of the call, and the current thread is interrupted.]]
[[Notes:] [`get()` is an ['interruption point].]]
]
[endsect]
[section:wait Member function `wait()`]
void wait();
[variablelist
[[Effects:] [If `*this` is associated with an asynchronous result, waits until the result is ready. If the result is not ready on
entry, and the result has a ['wait callback] set, that callback is invoked prior to waiting.]]
[[Throws:] [__future_uninitialized__ if `*this` is not associated with an asynchronous result. __thread_interrupted__ if the result
associated with `*this` is not ready at the point of the call, and the current thread is interrupted. Any exception thrown by the
['wait callback] if such a callback is called.]]
[[Postconditions:] [[shared_future_is_ready_link `this->is_ready()`] returns `true`. [shared_future_get_state_link
`this->get_state()`] returns __ready__.]]
[[Notes:] [`wait()` is an ['interruption point].]]
]
[endsect]
[section:timed_wait_duration Member function `timed_wait()`]
template<typename Duration>
bool timed_wait(Duration const& wait_duration);
[variablelist
[[Effects:] [If `*this` is associated with an asynchronous result, waits until the result is ready, or the time specified by
`wait_duration` has elapsed. If the result is not ready on entry, and the result has a ['wait callback] set, that callback is
invoked prior to waiting.]]
[[Returns:] [`true` if `*this` is associated with an asynchronous result, and that result is ready before the specified time has
elapsed, `false` otherwise.]]
[[Throws:] [__future_uninitialized__ if `*this` is not associated with an asynchronous result. __thread_interrupted__ if the result
associated with `*this` is not ready at the point of the call, and the current thread is interrupted. Any exception thrown by the
['wait callback] if such a callback is called.]]
[[Postconditions:] [If this call returned `true`, then [shared_future_is_ready_link `this->is_ready()`] returns `true` and
[shared_future_get_state_link `this->get_state()`] returns __ready__.]]
[[Notes:] [`timed_wait()` is an ['interruption point]. `Duration` must be a type that meets the Boost.DateTime time duration requirements.]]
]
[endsect]
[section:timed_wait_absolute Member function `timed_wait()`]
bool timed_wait(boost::system_time const& wait_timeout);
[variablelist
[[Effects:] [If `*this` is associated with an asynchronous result, waits until the result is ready, or the time point specified by
`wait_timeout` has passed. If the result is not ready on entry, and the result has a ['wait callback] set, that callback is invoked
prior to waiting.]]
[[Returns:] [`true` if `*this` is associated with an asynchronous result, and that result is ready before the specified time has
passed, `false` otherwise.]]
[[Throws:] [__future_uninitialized__ if `*this` is not associated with an asynchronous result. __thread_interrupted__ if the result
associated with `*this` is not ready at the point of the call, and the current thread is interrupted. Any exception thrown by the
['wait callback] if such a callback is called.]]
[[Postconditions:] [If this call returned `true`, then [shared_future_is_ready_link `this->is_ready()`] returns `true` and
[shared_future_get_state_link `this->get_state()`] returns __ready__.]]
[[Notes:] [`timed_wait()` is an ['interruption point].]]
]
[endsect]
[section:is_ready Member function `is_ready()`]
bool is_ready();
[variablelist
[[Effects:] [Checks to see if the asynchronous result associated with `*this` is set.]]
[[Returns:] [`true` if `*this` is associated with an asynchronous result, and that result is ready for retrieval, `false`
otherwise.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:has_value Member function `has_value()`]
bool has_value();
[variablelist
[[Effects:] [Checks to see if the asynchronous result associated with `*this` is set with a value rather than an exception.]]
[[Returns:] [`true` if `*this` is associated with an asynchronous result, that result is ready for retrieval, and the result is a
stored value, `false` otherwise.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:has_exception Member function `has_exception()`]
bool has_exception();
[variablelist
[[Effects:] [Checks to see if the asynchronous result associated with `*this` is set with an exception rather than a value.]]
[[Returns:] [`true` if `*this` is associated with an asynchronous result, that result is ready for retrieval, and the result is a
stored exception, `false` otherwise.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:get_state Member function `get_state()`]
future_state::state get_state();
[variablelist
[[Effects:] [Determine the state of the asynchronous result associated with `*this`, if any.]]
[[Returns:] [__uninitialized__ if `*this` is not associated with an asynchronous result. __ready__ if the asynchronous result
associated with `*this` is ready for retrieval, __waiting__ otherwise.]]
[[Throws:] [Nothing.]]
]
[endsect]
[endsect]
[section:promise `promise` class template]
template <typename R>
class promise
{
promise(promise & rhs);// = delete;
promise & operator=(promise & rhs);// = delete;
public:
// template <class Allocator> explicit promise(Allocator a);
promise();
~promise();
// Move support
promise(promise && rhs);
promise & operator=(promise&& rhs);
void swap(promise& other);
// Result retrieval
unique_future<R> get_future();
// Set the value
void set_value(R& r);
void set_value(R&& r);
void set_exception(boost::exception_ptr e);
template<typename F>
void set_wait_callback(F f);
};
[section:default_constructor Default Constructor]
promise();
[variablelist
[[Effects:] [Constructs a new __promise__ with no associated result.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:move_constructor Move Constructor]
promise(promise && other);
[variablelist
[[Effects:] [Constructs a new __promise__, and transfers ownership of the result associated with `other` to `*this`, leaving `other`
with no associated result.]]
[[Throws:] [Nothing.]]
[[Notes:] [If the compiler does not support rvalue-references, this is implemented using the boost.thread move emulation.]]
]
[endsect]
[section:move_assignment Move Assignment Operator]
promise& operator=(promise && other);
[variablelist
[[Effects:] [Transfers ownership of the result associated with `other` to `*this`, leaving `other` with no associated result. If there
was already a result associated with `*this`, and that result was not ['ready], sets any futures associated with that result to
['ready] with a __broken_promise__ exception as the result. ]]
[[Throws:] [Nothing.]]
[[Notes:] [If the compiler does not support rvalue-references, this is implemented using the boost.thread move emulation.]]
]
[endsect]
[section:destructor Destructor]
~promise();
[variablelist
[[Effects:] [Destroys `*this`. If there was a result associated with `*this`, and that result is not ['ready], sets any futures
associated with that task to ['ready] with a __broken_promise__ exception as the result.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:get_future Member Function `get_future()`]
unique_future<R> get_future();
[variablelist
[[Effects:] [If `*this` was not associated with a result, allocate storage for a new asynchronous result and associate it with
`*this`. Returns a __unique_future__ associated with the result associated with `*this`. ]]
[[Throws:] [__future_already_retrieved__ if the future associated with the task has already been retrieved. `std::bad_alloc` if any
memory necessary could not be allocated.]]
]
[endsect]
[section:set_value Member Function `set_value()`]
void set_value(R&& r);
void set_value(const R& r);
void promise<R&>::set_value(R& r);
void promise<void>::set_value();
[variablelist
[[Effects:] [If `*this` was not associated with a result, allocate storage for a new asynchronous result and associate it with
`*this`. Store the value `r` in the asynchronous result associated with `*this`. Any threads blocked waiting for the asynchronous
result are woken.]]
[[Postconditions:] [All futures waiting on the asynchronous result are ['ready] and __unique_future_has_value__ or
__shared_future_has_value__ for those futures shall return `true`.]]
[[Throws:] [__promise_already_satisfied__ if the result associated with `*this` is already ['ready]. `std::bad_alloc` if the memory
required for storage of the result cannot be allocated. Any exception thrown by the copy or move-constructor of `R`.]]
]
[endsect]
[section:set_exception Member Function `set_exception()`]
void set_exception(boost::exception_ptr e);
[variablelist
[[Effects:] [If `*this` was not associated with a result, allocate storage for a new asynchronous result and associate it with
`*this`. Store the exception `e` in the asynchronous result associated with `*this`. Any threads blocked waiting for the asynchronous
result are woken.]]
[[Postconditions:] [All futures waiting on the asynchronous result are ['ready] and __unique_future_has_exception__ or
__shared_future_has_exception__ for those futures shall return `true`.]]
[[Throws:] [__promise_already_satisfied__ if the result associated with `*this` is already ['ready]. `std::bad_alloc` if the memory
required for storage of the result cannot be allocated.]]
]
[endsect]
[section:set_wait_callback Member Function `set_wait_callback()`]
template<typename F>
void set_wait_callback(F f);
[variablelist
[[Preconditions:] [The expression `f(t)` where `t` is a lvalue of type __packaged_task__ shall be well-formed. Invoking a copy of
`f` shall have the same effect as invoking `f`]]
[[Effects:] [Store a copy of `f` with the asynchronous result associated with `*this` as a ['wait callback]. This will replace any
existing wait callback store alongside that result. If a thread subsequently calls one of the wait functions on a __unique_future__
or __shared_future__ associated with this result, and the result is not ['ready], `f(*this)` shall be invoked.]]
[[Throws:] [`std::bad_alloc` if memory cannot be allocated for the required storage.]]
]
[endsect]
[endsect]
[section:packaged_task `packaged_task` class template]
template<typename R>
class packaged_task
{
packaged_task(packaged_task&);// = delete;
packaged_task& operator=(packaged_task&);// = delete;
public:
// construction and destruction
template <class F>
explicit packaged_task(F const& f);
explicit packaged_task(R(*f)());
template <class F>
explicit packaged_task(F&& f);
// template <class F, class Allocator>
// explicit packaged_task(F const& f, Allocator a);
// template <class F, class Allocator>
// explicit packaged_task(F&& f, Allocator a);
~packaged_task()
{}
// move support
packaged_task(packaged_task&& other);
packaged_task& operator=(packaged_task&& other);
void swap(packaged_task& other);
// result retrieval
unique_future<R> get_future();
// execution
void operator()();
template<typename F>
void set_wait_callback(F f);
};
[section:task_constructor Task Constructor]
template<typename F>
packaged_task(F const &f);
packaged_task(R(*f)());
template<typename F>
packaged_task(F&&f);
[variablelist
[[Preconditions:] [`f()` is a valid expression with a return type convertible to `R`. Invoking a copy of `f` shall behave the same
as invoking `f`.]]
[[Effects:] [Constructs a new __packaged_task__ with a copy of `f` stored as the associated task.]]
[[Throws:] [Any exceptions thrown by the copy (or move) constructor of `f`. `std::bad_alloc` if memory for the internal data
structures could not be allocated.]]
]
[endsect]
[section:move_constructor Move Constructor]
packaged_task(packaged_task && other);
[variablelist
[[Effects:] [Constructs a new __packaged_task__, and transfers ownership of the task associated with `other` to `*this`, leaving `other`
with no associated task.]]
[[Throws:] [Nothing.]]
[[Notes:] [If the compiler does not support rvalue-references, this is implemented using the boost.thread move emulation.]]
]
[endsect]
[section:move_assignment Move Assignment Operator]
packaged_task& operator=(packaged_task && other);
[variablelist
[[Effects:] [Transfers ownership of the task associated with `other` to `*this`, leaving `other` with no associated task. If there
was already a task associated with `*this`, and that task has not been invoked, sets any futures associated with that task to
['ready] with a __broken_promise__ exception as the result. ]]
[[Throws:] [Nothing.]]
[[Notes:] [If the compiler does not support rvalue-references, this is implemented using the boost.thread move emulation.]]
]
[endsect]
[section:destructor Destructor]
~packaged_task();
[variablelist
[[Effects:] [Destroys `*this`. If there was a task associated with `*this`, and that task has not been invoked, sets any futures
associated with that task to ['ready] with a __broken_promise__ exception as the result.]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:get_future Member Function `get_future()`]
unique_future<R> get_future();
[variablelist
[[Effects:] [Returns a __unique_future__ associated with the result of the task associated with `*this`. ]]
[[Throws:] [__task_moved__ if ownership of the task associated with `*this` has been moved to another instance of
__packaged_task__. __future_already_retrieved__ if the future associated with the task has already been retrieved.]]
]
[endsect]
[section:call_operator Member Function `operator()()`]
void operator()();
[variablelist
[[Effects:] [Invoke the task associated with `*this` and store the result in the corresponding future. If the task returns normally,
the return value is stored as the asynchronous result, otherwise the exception thrown is stored. Any threads blocked waiting for the
asynchronous result associated with this task are woken.]]
[[Postconditions:] [All futures waiting on the asynchronous result are ['ready]]]
[[Throws:] [__task_moved__ if ownership of the task associated with `*this` has been moved to another instance of
__packaged_task__. __task_already_started__ if the task has already been invoked.]]
]
[endsect]
[section:set_wait_callback Member Function `set_wait_callback()`]
template<typename F>
void set_wait_callback(F f);
[variablelist
[[Preconditions:] [The expression `f(t)` where `t` is a lvalue of type __packaged_task__ shall be well-formed. Invoking a copy of
`f` shall have the same effect as invoking `f`]]
[[Effects:] [Store a copy of `f` with the task associated with `*this` as a ['wait callback]. This will replace any existing wait
callback store alongside that task. If a thread subsequently calls one of the wait functions on a __unique_future__ or
__shared_future__ associated with this task, and the result of the task is not ['ready], `f(*this)` shall be invoked.]]
[[Throws:] [__task_moved__ if ownership of the task associated with `*this` has been moved to another instance of
__packaged_task__.]]
]
[endsect]
[endsect]
[section:wait_for_any Non-member function `wait_for_any()`]
template<typename Iterator>
Iterator wait_for_any(Iterator begin,Iterator end);
template<typename F1,typename F2>
unsigned wait_for_any(F1& f1,F2& f2);
template<typename F1,typename F2,typename F3>
unsigned wait_for_any(F1& f1,F2& f2,F3& f3);
template<typename F1,typename F2,typename F3,typename F4>
unsigned wait_for_any(F1& f1,F2& f2,F3& f3,F4& f4);
template<typename F1,typename F2,typename F3,typename F4,typename F5>
unsigned wait_for_any(F1& f1,F2& f2,F3& f3,F4& f4,F5& f5);
[variablelist
[[Preconditions:] [The types `Fn` shall be specializations of
__unique_future__ or __shared_future__, and `Iterator` shall be a
forward iterator with a `value_type` which is a specialization of
__unique_future__ or __shared_future__.]]
[[Effects:] [Waits until at least one of the specified futures is ['ready].]]
[[Returns:] [The range-based overload returns an `Iterator` identifying the first future in the range that was detected as
['ready]. The remaining overloads return the zero-based index of the first future that was detected as ['ready] (first parameter =>
0, second parameter => 1, etc.).]]
[[Throws:] [__thread_interrupted__ if the current thread is interrupted. Any exception thrown by the ['wait callback] associated
with any of the futures being waited for. `std::bad_alloc` if memory could not be allocated for the internal wait structures.]]
[[Notes:] [`wait_for_any()` is an ['interruption point].]]
]
[endsect]
[section:wait_for_all Non-member function `wait_for_all()`]
template<typename Iterator>
void wait_for_all(Iterator begin,Iterator end);
template<typename F1,typename F2>
void wait_for_all(F1& f1,F2& f2);
template<typename F1,typename F2,typename F3>
void wait_for_all(F1& f1,F2& f2,F3& f3);
template<typename F1,typename F2,typename F3,typename F4>
void wait_for_all(F1& f1,F2& f2,F3& f3,F4& f4);
template<typename F1,typename F2,typename F3,typename F4,typename F5>
void wait_for_all(F1& f1,F2& f2,F3& f3,F4& f4,F5& f5);
[variablelist
[[Preconditions:] [The types `Fn` shall be specializations of
__unique_future__ or __shared_future__, and `Iterator` shall be a
forward iterator with a `value_type` which is a specialization of
__unique_future__ or __shared_future__.]]
[[Effects:] [Waits until all of the specified futures are ['ready].]]
[[Throws:] [Any exceptions thrown by a call to `wait()` on the specified futures.]]
[[Notes:] [`wait_for_all()` is an ['interruption point].]]
]
[endsect]
[endsect]

View File

@@ -1,187 +0,0 @@
[/
(C) Copyright 2008-9 Anthony Williams.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
]
[section:futures Futures]
[template future_state_link[link_text] [link thread.synchronization.futures.reference.future_state [link_text]]]
[def __uninitialized__ [future_state_link `boost::future_state::uninitialized`]]
[def __ready__ [future_state_link `boost::future_state::ready`]]
[def __waiting__ [future_state_link `boost::future_state::waiting`]]
[def __future_uninitialized__ `boost::future_uninitialized`]
[def __broken_promise__ `boost::broken_promise`]
[def __future_already_retrieved__ `boost::future_already_retrieved`]
[def __task_moved__ `boost::task_moved`]
[def __task_already_started__ `boost::task_already_started`]
[def __promise_already_satisfied__ `boost::promise_already_satisfied`]
[def __thread_interrupted__ `boost::thread_interrupted`]
[template unique_future_link[link_text] [link thread.synchronization.futures.reference.unique_future [link_text]]]
[def __unique_future__ [unique_future_link `boost::unique_future`]]
[template unique_future_get_link[link_text] [link thread.synchronization.futures.reference.unique_future.get [link_text]]]
[def __unique_future_get__ [unique_future_get_link `boost::unique_future<R>::get()`]]
[template unique_future_wait_link[link_text] [link thread.synchronization.futures.reference.unique_future.wait [link_text]]]
[def __unique_future_wait__ [unique_future_wait_link `boost::unique_future<R>::wait()`]]
[template unique_future_is_ready_link[link_text] [link thread.synchronization.futures.reference.unique_future.is_ready [link_text]]]
[def __unique_future_is_ready__ [unique_future_is_ready_link `boost::unique_future<R>::is_ready()`]]
[template unique_future_has_value_link[link_text] [link thread.synchronization.futures.reference.unique_future.has_value [link_text]]]
[def __unique_future_has_value__ [unique_future_has_value_link `boost::unique_future<R>::has_value()`]]
[template unique_future_has_exception_link[link_text] [link thread.synchronization.futures.reference.unique_future.has_exception [link_text]]]
[def __unique_future_has_exception__ [unique_future_has_exception_link `boost::unique_future<R>::has_exception()`]]
[template unique_future_get_state_link[link_text] [link thread.synchronization.futures.reference.unique_future.get_state [link_text]]]
[def __unique_future_get_state__ [unique_future_get_state_link `boost::unique_future<R>::get_state()`]]
[template shared_future_link[link_text] [link thread.synchronization.futures.reference.shared_future [link_text]]]
[def __shared_future__ [shared_future_link `boost::shared_future`]]
[template shared_future_get_link[link_text] [link thread.synchronization.futures.reference.shared_future.get [link_text]]]
[def __shared_future_get__ [shared_future_get_link `boost::shared_future<R>::get()`]]
[template shared_future_wait_link[link_text] [link thread.synchronization.futures.reference.shared_future.wait [link_text]]]
[def __shared_future_wait__ [shared_future_wait_link `boost::shared_future<R>::wait()`]]
[template shared_future_is_ready_link[link_text] [link thread.synchronization.futures.reference.shared_future.is_ready [link_text]]]
[def __shared_future_is_ready__ [shared_future_is_ready_link `boost::shared_future<R>::is_ready()`]]
[template shared_future_has_value_link[link_text] [link thread.synchronization.futures.reference.shared_future.has_value [link_text]]]
[def __shared_future_has_value__ [shared_future_has_value_link `boost::shared_future<R>::has_value()`]]
[template shared_future_has_exception_link[link_text] [link thread.synchronization.futures.reference.shared_future.has_exception [link_text]]]
[def __shared_future_has_exception__ [shared_future_has_exception_link `boost::shared_future<R>::has_exception()`]]
[template shared_future_get_state_link[link_text] [link thread.synchronization.futures.reference.shared_future.get_state [link_text]]]
[def __shared_future_get_state__ [shared_future_get_state_link `boost::shared_future<R>::get_state()`]]
[template promise_link[link_text] [link thread.synchronization.futures.reference.promise [link_text]]]
[def __promise__ [promise_link `boost::promise`]]
[template packaged_task_link[link_text] [link thread.synchronization.futures.reference.packaged_task [link_text]]]
[def __packaged_task__ [packaged_task_link `boost::packaged_task`]]
[template wait_for_any_link[link_text] [link thread.synchronization.futures.reference.wait_for_any [link_text]]]
[def __wait_for_any__ [wait_for_any_link `boost::wait_for_any()`]]
[template wait_for_all_link[link_text] [link thread.synchronization.futures.reference.wait_for_all [link_text]]]
[def __wait_for_all__ [wait_for_all_link `boost::wait_for_all()`]]
[section:overview Overview]
The futures library provides a means of handling synchronous future values, whether those values are generated by another thread, or
on a single thread in response to external stimuli, or on-demand.
This is done through the provision of four class templates: __unique_future__ and __shared_future__ which are used to retrieve the
asynchronous results, and __promise__ and __packaged_task__ which are used to generate the asynchronous results.
An instance of __unique_future__ holds the one and only reference to a result. Ownership can be transferred between instances using
the move constructor or move-assignment operator, but at most one instance holds a reference to a given asynchronous result. When
the result is ready, it is returned from __unique_future_get__ by rvalue-reference to allow the result to be moved or copied as
appropriate for the type.
On the other hand, many instances of __shared_future__ may reference the same result. Instances can be freely copied and assigned,
and __shared_future_get__ returns a `const` reference so that multiple calls to __shared_future_get__ are safe. You can move an
instance of __unique_future__ into an instance of __shared_future__, thus transferring ownership of the associated asynchronous
result, but not vice-versa.
You can wait for futures either individually or with one of the __wait_for_any__ and __wait_for_all__ functions.
[endsect]
[section:creating Creating asynchronous values]
You can set the value in a future with either a __promise__ or a __packaged_task__. A __packaged_task__ is a callable object that
wraps a function or callable object. When the packaged task is invoked, it invokes the contained function in turn, and populates a
future with the return value. This is an answer to the perennial question: "how do I return a value from a thread?": package the
function you wish to run as a __packaged_task__ and pass the packaged task to the thread constructor. The future retrieved from the
packaged task can then be used to obtain the return value. If the function throws an exception, that is stored in the future in
place of the return value.
int calculate_the_answer_to_life_the_universe_and_everything()
{
return 42;
}
boost::packaged_task<int> pt(calculate_the_answer_to_life_the_universe_and_everything);
boost::unique_future<int> fi=pt.get_future();
boost::thread task(boost::move(pt)); // launch task on a thread
fi.wait(); // wait for it to finish
assert(fi.is_ready());
assert(fi.has_value());
assert(!fi.has_exception());
assert(fi.get_state()==boost::future_state::ready);
assert(fi.get()==42);
A __promise__ is a bit more low level: it just provides explicit functions to store a value or an exception in the associated
future. A promise can therefore be used where the value may come from more than one possible source, or where a single operation may
produce multiple values.
boost::promise<int> pi;
boost::unique_future<int> fi;
fi=pi.get_future();
pi.set_value(42);
assert(fi.is_ready());
assert(fi.has_value());
assert(!fi.has_exception());
assert(fi.get_state()==boost::future_state::ready);
assert(fi.get()==42);
[endsect]
[section:lazy_futures Wait Callbacks and Lazy Futures]
Both __promise__ and __packaged_task__ support ['wait callbacks] that are invoked when a thread blocks in a call to `wait()` or
`timed_wait()` on a future that is waiting for the result from the __promise__ or __packaged_task__, in the thread that is doing the
waiting. These can be set using the `set_wait_callback()` member function on the __promise__ or __packaged_task__ in question.
This allows ['lazy futures] where the result is not actually computed until it is needed by some thread. In the example below, the
call to `f.get()` invokes the callback `invoke_lazy_task`, which runs the task to set the value. If you remove the call to
`f.get()`, the task is not ever run.
int calculate_the_answer_to_life_the_universe_and_everything()
{
return 42;
}
void invoke_lazy_task(boost::packaged_task<int>& task)
{
try
{
task();
}
catch(boost::task_already_started&)
{}
}
int main()
{
boost::packaged_task<int> task(calculate_the_answer_to_life_the_universe_and_everything);
task.set_wait_callback(invoke_lazy_task);
boost::unique_future<int> f(task.get_future());
assert(f.get()==42);
}
[endsect]
[include future_ref.qbk]
[endsect]

View File

@@ -1,12 +1,163 @@
<!-- Copyright (c) 2002-2003 Beman Dawes, William E. Kempf.
Subject to the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
-->
<html>
<head>
<meta http-equiv="refresh" content="0; URL=../../../doc/html/thread.html">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads</title>
</head>
<body>
Automatic redirection failed, please go to <a href="../../../doc/html/thread.html">../../../doc/html/thread.html</a>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Index</h2>
</td>
</tr>
</table>
<hr>
<h2>Contents</h2>
<dl class="index">
<dt><a href="overview.html">Overview</a></dt>
<dt><a href="mutex_concept.html">Mutex Concepts</a></dt>
<dl class="index">
<dt><a href="mutex_concept.html#Mutex">Mutex</a></dt>
<dt><a href="mutex_concept.html#TryMutex">TryMutex</a></dt>
<dt><a href="mutex_concept.html#TimedMutex">TimedMutex</a></dt>
</dl>
<dt><a href="lock_concept.html">Lock Concepts</a></dt>
<dl class="index">
<dt><a href="lock_concept.html#Lock">Lock</a></dt>
<dt><a href="lock_concept.html#ScopedLock">ScopedLock</a></dt>
<dt><a href="lock_concept.html#ScopedTryLock">ScopedTryLock</a></dt>
<dt><a href="lock_concept.html#ScopedTimedLock">ScopedTimedLock</a></dt>
</dl>
<dt>Reference</dt>
<dl class="index">
<dt><a href="barrier.html"><code>&lt;boost/thread/barrier.hpp&gt;</code></a></dt>
<dl class="index">
<dt><a href="barrier.html#classes">Classes</a></dt>
<dl class="index">
<dt><a href="barrier.html#class-barrier"><code>barrier</code></a></dt>
</dl>
</dl>
<dt><a href="condition.html"><code>&lt;boost/thread/condition.hpp&gt;</code></a></dt>
<dl class="index">
<dt><a href="condition.html#classes">Classes</a></dt>
<dl class="index">
<dt><a href="condition.html#class-condition"><code>condition</code></a></dt>
</dl>
</dl>
</dl>
<dl class="index">
<dt><a href="exceptions.html"><code>&lt;boost/thread/exceptions.hpp&gt;</code></a></dt>
<dl class="index">
<dt><a href="exceptions.html#classes">Classes</a></dt>
<dl class="index">
<dt><a href="exceptions.html#class-lock_error"><code>lock_error</code></a></dt>
<dt><a href="exceptions.html#class-thread_resource_error"><code>thread_resource_error</code></a></dt>
</dl>
</dl>
</dl>
<dl class="index">
<dt><a href="mutex.html"><code>&lt;boost/thread/mutex.hpp&gt;</code></a></dt>
<dl class="index">
<dt><a href="mutex.html#classes">Classes</a></dt>
<dl class="index">
<dt><a href="mutex.html#class-mutex"><code>mutex</code></a></dt>
<dt><a href="mutex.html#class-try_mutex"><code>try_mutex</code></a></dt>
<dt><a href="mutex.html#class-timed_mutex"><code>timed_mutex</code></a></dt>
</dl>
</dl>
</dl>
<dl class="index">
<dt><a href="once.html"><code>&lt;boost/thread/once.hpp&gt;</code></a></dt>
<dl class="index">
<dt><a href="once.html#macros">Macros</a></dt>
<dl class="index">
<dt><a href="once.html#macro-BOOST_ONCE_INIT"><code>BOOST_ONCE_INIT</code></a></dt>
</dl>
<dt><a href="once.html#types">Types</a></dt>
<dl class="index">
<dt><a href="once.html#type-once_flag"><code>once_flag</code></a></dt>
</dl>
<dt><a href="once.html#functions">Functions</a></dt>
<dl class="index">
<dt><a href="once.html#function-call_once"><code>call_once</code></a></dt>
</dl>
</dl>
</dl>
<dl class="index">
<dt><a href="recursive_mutex.html"><code>&lt;boost/thread/recursive_mutex.hpp&gt;</code></a></dt>
<dl class="index">
<dt><a href="recursive_mutex.html#classes">Classes</a></dt>
<dl class="index">
<dt><a href="recursive_mutex.html#class-recursive_mutex"><code>recursive_mutex</code></a></dt>
<dt><a href="recursive_mutex.html#class-recursive_try_mutex"><code>recursive_try_mutex</code></a></dt>
<dt><a href="recursive_mutex.html#class-recursive_timed_mutex"><code>recursive_timed_mutex</code></a></dt>
</dl>
</dl>
</dl>
<dl class="index">
<dt><a href="thread.html"><code>&lt;boost/thread/thread.hpp&gt;</code></a></dt>
<dl class="index">
<dt><a href="thread.html#classes">Classes</a></dt>
<dl class="index">
<dt><a href="thread.html#class-thread"><code>thread</code></a></dt>
<dt><a href="thread.html#class-thread_group"><code>thread_group</code></a></dt>
</dl>
</dl>
</dl>
<dl class="index">
<dt><a href="tss.html"><code>&lt;boost/thread/tss.hpp&gt;</code></a></dt>
<dl class="index">
<dt><a href="tss.html#classes">Classes</a></dt>
<dl class="index">
<dt><a href="tss.html#class-thread_specific_ptr"><code>thread_specific_ptr</code></a></dt>
</dl>
</dl>
</dl>
<dl class="index">
<dt><a href="xtime.html"><code>&lt;boost/thread/xtime.hpp&gt;</code></a></dt>
<dl class="index">
<dt><a href="xtime.html#values">Values</a></dt>
<dl class="page-index">
<dt><a href="xtime.html#value-spec"><code>TIME_UTC</code></a></dt>
</dl>
<dt><a href="xtime.html#classes">Classes</a></dt>
<dl class="page-index">
<dt><a href="xtime.html#class-xtime"><code>xtime</code></a></dt>
</dl>
<dt><a href="xtime.html#functions">Functions</a></dt>
<dl class="page-index">
<dt><a href="xtime.html#function-xtime_get"><code>xtime_get</code></a></dt>
</dl>
</dl>
</dl>
<dt><a href="configuration.html">Configuration Information</a></dt>
<dt><a href="build.html">Building and Testing</a></dt>
<dt><a href="introduction.html">Introduction to Design</a></dt>
<dt><a href="rationale.html">Rationale</a></dt>
<dt><a href="definitions.html">Definitions</a></dt>
<dt><a href="faq.html">Frequently Asked Questions (FAQs)</a></dt>
<dt><a href="bibliography.html">Bibliography</a></dt>
<dt><a href="acknowledgments.html">Acknowledgments</a></dt>
</dl>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

159
doc/introduction.html Normal file
View File

@@ -0,0 +1,159 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Introduction to Design</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Introduction to Design</h2>
</td>
</tr>
</table>
<hr>
<dl class="page-index">
<dt><a href="#motivation">Motivation</a></dt>
<dt><a href="#goals">Goals</a></dt>
<dt><a href="#phases">Iterative Phases</a></dt>
<dl class="page-index">
<dt><a href="#phase1">Phase 1, Synchronization Primitives</a></dt>
<dt><a href="#phase2">Phase 2, Thread Management and Thread Specific Storage</a></dt>
<dt><a href="#next-phase">The Next Phase</a></dt>
</dl>
</dl>
<h2><a name="motivation"></a>Motivation</h2>
<p>With client/server and three-tier architectures becoming common place in today&#39;s
world, it&#39;s becoming increasingly important for programs to be able to handle
parallel processing. Modern day operating systems usually provide some support
for this through native thread APIs. Unfortunately, writing portable code that
makes use of parallel processing in C++ is made very difficult by a lack of
a standard interface for these native APIs. Further, these APIs are almost universally
C APIs and fail to take advantage of C++&#39;s strengths, or to address C++&#39;s
issues.</p>
<p>The <b>Boost.Threads</b> library is an attempt to define a portable interface
for writing parallel processes in C++.</p>
<h2><a name="goals"></a>Goals</h2>
<p>The <b>Boost.Threads</b> library has several goals that should help to set
it apart from other solutions. These goals are listed in order of precedence
with full descriptions below.</p>
<ul>
<li> <b>Portability</b>
<p><b>Boost.Threads</b> was designed to be highly portable. The goal is for
the interface to be easily implemented on any platform that supports threads,
and possibly even on platforms without native thread support.</p>
</li>
<li> <b>Safety</b>
<p><b>Boost.Threads</b> was designed to be as safe as possible. Writing <a href="definitions.html#Thread-safe">thread-safe</a>
code is very difficult and successful libraries must strive to insulate
the programmer from dangerous constructs as much as possible. This is accomplished
in several ways:</p>
<ul>
<li>
<p align="left">C++ language features are used make correct usage easy
(if possible, the default) and error-prone impossible or at least more
difficult. For example, see the <a href="mutex_concept.html">Mutex</a>
and <a href="lock_concept.html">Lock</a> designs, and how note how they
interact.</p>
</li>
<li>
<p align="left">Certain traditional concurrent programming features are
considered so error-prone that they are not provided at all. For example,
see the <a
href="rationale.html#Events">Events Not Provided</a> rationale.</p>
</li>
<li>
<p align="left">Dangerous features, or features which may be misused,
are identified as such in the documentation to make users aware of potential
pitfalls.</p>
</li>
</ul>
</li>
<li> <b>Flexibility</b>
<p><b>Boost.Threads</b> was designed to be flexible. This goal is often at
odds with <i>safety</i>. When functionality might be compromised by the
desire to keep the interface safe, <b> Boost.Threads</b> has been designed
to provide the functionality, but to make it&#39;s use prohibitive for general
use. In other words, the interfaces have been designed such that it's usually
obvious when something is unsafe, and the documentation is written to explain
why.</p>
</li>
<li> <b>Efficiency</b>
<p><b>Boost.Threads</b> was designed to be as efficient as possible. When
building a library on top of another library there is always a danger that
the result will be so much slower than the &quot;native&quot; API that programmers
are inclined to ignore the higher level API. <b>Boost.Threads</b> was designed
to minimize the chances of this occurring. The interfaces have been crafted
to allow an implementation the greatest chance of being as efficient as
possible. This goal is often at odds with the goal for <i>safety</i>. Every
effort was made to ensure efficient implementations, but when in conflict
<i>safety</i> has always taken precedence.</p>
</li>
</ul>
<h2><a name="phases"></a>Iterative Phases</h2>
<p>Another goal of <b>Boost.Threads</b> was to take a dynamic, iterative approach
in its development. The computing industry is still exploring the concepts of
parallel programming. Most thread libraries supply only simple primitive concepts
for thread synchronization. These concepts are very simple, but they are very
difficult to use safely or to provide formal proofs for constructs built on
top of them. There has been a lot of research in other concepts, such as in
&quot;Communicating Sequential Processes.&quot; <b>Boost.Threads</b> was designed
in iterative steps, providing the building blocks necessary for the next step,
and giving the researcher the tools necessary to explore new concepts in a portable
manner.</p>
<p>Given the goal of following a dynamic, iterative approach <b> Boost.Threads</b>
shall go through several growth cycles. Each phase in its development shall
be roughly documented here.</p>
<h3><a name="phase1"></a>Phase 1, Synchronization Primitives</h3>
<p>Boost is all about providing high quality libraries with implementations for
many platforms. Unfortunately, there&#39;s a big problem faced by developers
wishing to supply such high quality libraries, namely thread-safety. The C++
standard doesn&#39;t address threads at all, but real world programs often make
use of native threading support. A portable library that doesn&#39;t address
the issue of thread-safety is there for not much help to a programmer who wants
to use the library in his multithreaded application. So there&#39;s a very great
need for portable primitives that will allow the library developer to create
<a href="definitions.html#Thread-safe"> thread-safe</a> implementations. This
need far out weighs the need for portable methods to create and manage threads.</p>
<p>Because of this need, the first phase of <b>Boost.Threads</b> focuses solely
on providing portable primitive concepts for thread synchronization. Types provided
in this phase include the <a href="mutex.html"> mutex/try_mutex/timed_mutex</a>,
<a href="recursive_mutex.html"> recursive_mutex/recursive_try_mutex/recursive_timed_mutex</a>
and <a href="exceptions.html#class-lock_error">lock_error</a>. These are considered
the &quot;core&quot; synchronization primitives, though there are others that
will be added in later phases.</p>
<h3><a name="phase2"></a>Phase 2, Thread Management and Thread Specific Storage</h3>
<p>This phase addresses the creation and management of threads and provides a
mechanism for thread specific storage (data associated with a thread instance).
Thread management is a tricky issue in C++, so this phase addresses only the
basic needs of multithreaded program. Later phases are likely to add additional
functionality in this area. This phase of <b>Boost.Threads</b> adds the <a href="thread.html">thread</a>
and <a href="tss.html#class-thread_specific_ptr">thread_specific_ptr</a> types.
With these additions the <b>Boost.Threads</b> library can be considered minimal
but complete.</p>
<h3><a name="next-phase"></a>The Next Phase</h3>
<p>The next phase will address more advanced synchronization concepts, such as
read/write mutexes and barriers.</p>
<hr>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

194
doc/lock_concept.html Normal file
View File

@@ -0,0 +1,194 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - ScopedLock Concept</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">ScopedLock Concept</h2>
</td>
</tr>
</table>
<hr>
<dl class="page-index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#concept-requirements">Concept Requirements</a></dt>
<dl class="page-index">
<dt><a href="#Lock-concept">Lock Concept</a></dt>
<dt><a href="#ScopedLock-concept">ScopedLock Concept</a></dt>
<dt><a href="#ScopedTryLock-concept">ScopedTryLock Concept</a></dt>
<dt><a href="#ScopedTimedLock-concept">ScopedTimedLock Concept</a></dt>
</dl>
</dl>
<h2><a name="introduction"></a>Introduction</h2>
<p>A lock object provides a safe means for locking and unlocking a mutex object
(an object whose type is a model of <a href="mutex_concept.html">Mutex</a> or
one of its refinements). In other words they are an implementation of the <i>Scoped
Locking</i> <a href="bibliography.html#Schmidt-00">[Schmidt 00]</a> pattern.
The <a href="#ScopedLock-concept">ScopedLock</a> concept, with <a href="#ScopedTryLock-concept">ScopedTryLock</a>
and <a href="#ScopedTimedLock-concept">ScopedTimedLock</a> refinements, formalize
the requirements.</p>
<p>Lock objects are constructed with a reference to a mutex object and typically
acquire ownership of the mutex object by setting its state to locked. They also
ensure ownership is relinquished in the destructor. Lock objects also expose
functions to query the lock status and to manually lock and unlock the mutex
object.</p>
<p>Lock objects are meant to be short lived, expected to be used at block scope
only. The lock objects are not <a href="definitions.html#definition-thread-safe">thread-safe</a>.
Lock objects must maintain state to indicate whether or not they&#39;ve been
locked and this state is not protected by any synchronization concepts. For
this reason a lock object should never be shared between multiple threads.</p>
<h2><a name="concept-requirements"></a>Concept Requirements</h2>
<h3><a name="Lock-concept"></a>Lock Concept</h3>
<p>For a Lock type <code>L</code> and an object <code>lk</code> and const object
<code>clk</code> of that type, the following expressions must be well-formed
and have the indicated effects.</p>
<table summary="Lock expressions" border="1" cellpadding="5">
<tr>
<td><b>Expression</b></td>
<td><b>Effects</b></td>
</tr>
<tr>
<td valign="top"><code>(&amp;lk)-&gt;~L();</code></td>
<td><code>if (locked()) unlock();</code></td>
</tr>
<tr>
<td valign="top"><code>(&amp;clk)-&gt;operator const void*()</code></td>
<td>Returns type void*, non-zero if if the associated mutex object has been
locked by <code>clk</code>, otherwise 0.</td>
</tr>
<tr>
<td valign="top"><code>clk.locked()</code></td>
<td>Returns a <code>bool</code>, <code>(&amp;clk)-&gt;operator const void*()
!= 0</code></td>
</tr>
<tr>
<td valign="top"><code>lk.lock()</code></td>
<td>Throws <code>lock_error</code> if <code>locked()</code>. If the associated
mutex object is already locked by some other thread, places the current
thread in the <a href="definitions.html#State">Blocked</a> state until the
associated mutex is unlocked, after which the current thread is placed in
the <a href="definitions.html#State"> Ready</a> state, eventually to be
returned to the <a href="definitions.html#State">Running</a> state. If the
associated mutex object is already locked by the same thread the behavior
is dependent on the <a href="mutex_concept.html#locking-strategies">locking
strategy</a> of the associated mutex object.<br>
Postcondition: <code>locked() == true</code></td>
</tr>
<tr>
<td valign="top"><code>lk.unlock()</code></td>
<td>If <code>!locked()</code>, throws <code>lock_error</code>, otherwise unlocks
the associated mutex.<br>
Postcondition: <code>!locked()</code></td>
</tr>
</table>
<h3><a name="ScopedLock-concept"></a>ScopedLock Concept</h3>
<p>A ScopedLock is a refinement of <a href="#Lock">Lock</a>. For a ScopedLock
type <code>L</code> and an object <code>lk</code> of that type, and an object
<code>m</code> of a type meeting the <a href="mutex_concept.html#Mutex-concept">Mutex</a>
requirements, and an object <code>b</code> of type <code>bool</code>, the following
expressions must be well-formed and have the indicated effects.</p>
<table summary="ScopedLock expressions" border="1" cellpadding="5">
<tr>
<td><b>Expression</b></td>
<td><b>Effects</b></td>
</tr>
<tr>
<td valign="top"><code>L lk(m);</code></td>
<td>Constructs an object <code>lk</code>, and associates mutex object <code>m</code>
with it, then calls <code>lock()</code></td>
</tr>
<tr>
<td valign="top"><code>L lk(m,b);</code></td>
<td>Constructs an object <code>lk</code>, and associates mutex object <code>m</code>
with it, then if <code>b</code>, calls <code>lock()</code></td>
</tr>
</table>
<h3><a name="ScopedTryLock-concept"></a>ScopedTryLock Concept</h3>
<p>A ScopedTryLock is a refinement of <a href="#Lock-concept">Lock</a>. For a
ScopedTryLock type <code>L</code> and an object <code>lk</code> of that type,
and an object <code>m</code> of a type meeting the <a href="mutex_concept.html#TryMutex-concept">TryMutex</a>
requirements, and an object <code>b</code> of type <code>bool</code>, the following
expressions must be well-formed and have the indicated effects.</p>
<table summary="ScopedTryLock expressions" border="1" cellpadding="5">
<tr>
<td><b>Expression</b></td>
<td><b>Effects</b></td>
</tr>
<tr>
<td valign="top"><code>L lk(m);</code></td>
<td>Constructs an object <code>lk</code>, and associates mutex object <code>m</code>
with it, then calls <code>try_lock()</code></td>
</tr>
<tr>
<td valign="top"><code>L lk(m,b);</code></td>
<td>Constructs an object <code>lk</code>, and associates mutex object <code>m</code>
with it, then if <code>b</code>, calls <code> lock()</code></td>
</tr>
<tr>
<td valign="top"><code>lk.try_lock()</code></td>
<td>If locked(), throws <code>lock_error</code>. Makes a non-blocking attempt
to lock the associated mutex object, returning <code>true</code> if the
lock attempt is successful, otherwise <code>false</code>. If the associated
mutex object is already locked by the same thread the behavior is dependent
on the <a href="mutex_concept.html#locking-strategies">locking strategy</a>
of the associated mutex object.</td>
</tr>
</table>
<h3><a name="ScopedTimedLock-concept"></a>ScopedTimedLock Concept</h3>
<p>A ScopedTimedLock is a refinement of <a href="#Lock">Lock</a>. For a ScopedTimedLock
type <code>L</code> and an object <code>lk</code> of that type, and an object
<code>m</code> of a type meeting the <a href="mutex_concept.html#TimedMutex">TimedMutex</a>
requirements, and an object <code>b</code> of type <code>bool</code>, and an
object <code>t</code> of type <code><a href="xtime.html"> xtime</a></code>,
the following expressions must be well-formed and have the indicated effects.</p>
<table summary="ScopedTimedLock expressions" border="1" cellpadding=
"5">
<tr>
<td><b>Expression</b></td>
<td><b>Effects</b></td>
</tr>
<tr>
<td valign="top"><code>L lk(m,t);</code></td>
<td>Constructs an object <code>lk</code>, and associates mutex object <code>m</code>
with it, then calls <code> timed_lock(t)</code></td>
</tr>
<tr>
<td valign="top"><code>L lk(m,b);</code></td>
<td>Constructs an object <code>lk</code>, and associates mutex object <code>m</code>
with it, then if <code>b</code>, calls <code> lock()</code></td>
</tr>
<tr>
<td valign="top"><code>lk.timed_lock(t)</code></td>
<td>If locked(), throws lock_error. Makes a blocking attempt to lock the associated
mutex object, and returns <code>true</code> if successful within the specified
time <code>t</code>, otherwise <code>false</code>. If the associated mutex
object is already locked by the same thread the behavior is dependent on
the <a href="mutex_concept.html#locking-strategies">locking strategy</a>
of the associated mutex object.</td>
</tr>
</table>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

243
doc/mutex.html Normal file
View File

@@ -0,0 +1,243 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Header &lt;boost/thread/mutex.hpp&gt;</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Header &lt;<a href="../../../boost/thread/mutex.hpp">boost/thread/mutex.hpp</a>&gt;</h2>
</td>
</tr>
</table>
<hr>
<h2>Contents</h2>
<dl class="page-index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#classes">Classes</a></dt>
<dl class="page-index">
<dt><a href="#class-mutex">Class <code>mutex</code></a></dt>
<dl class="page-index">
<dt><a href="#class-mutex-synopsis">Class <code>mutex</code> synopsis</a></dt>
<dt><a href="#class-mutex-ctors">Class <code>mutex</code> constructors and
destructor</a></dt>
</dl>
</dl>
<dl class="page-index">
<dt><a href="#class-try_mutex">Class <code>try_mutex</code></a></dt>
<dl class="page-index">
<dt><a href="#class-try_mutex-synopsis">Class <code>try_mutex</code> synopsis</a></dt>
<dt><a href="#class-try_mutex-ctors">Class <code>try_mutex</code> constructors
and destructor</a></dt>
</dl>
</dl>
<dl class="page-index">
<dt><a href="#class-timed_mutex">Class <code>timed_mutex</code></a></dt>
<dl class="page-index">
<dt><a href="#class-timed_mutex-synopsis">Class <code>timed_mutex</code>
synopsis</a></dt>
<dt><a href="#class-timed_mutex-ctors">Class <code>timed_mutex</code> constructors
and destructor</a></dt>
</dl>
</dl>
<dt><a href="#examples">Example(s)</a></dt>
</dl>
<hr>
<h2><a name="introduction"></a>Introduction</h2>
<p>Include the header &lt;<a href="../../../boost/thread/mutex.hpp">boost/thread/mutex.hpp</a>&gt;
to define the <code><a href="#mutex Synopsis">mutex</a></code>, <code><a href=
"#try_mutex Synopsis">try_mutex</a></code> and <code><a href=
"#timed_mutex Synopsis">timed_mutex</a></code> classes.</p>
<p>The <code><a href="#mutex Synopsis">mutex</a></code>, <code><a href=
"#try_mutex Synopsis">try_mutex</a></code> and <code><a href=
"#timed_mutex Synopsis">timed_mutex</a></code> classes are models of <a href="mutex_concept.html#Mutex-concept">Mutex</a>,
<a href="mutex_concept.html#TryMutex-concept">TryMutex</a>, and <a href="mutex_concept.html#TimedMutex-concept">TimedMutex</a>
respectively. These types should be used to non-recursively synchronize access
to shared resources. For recursive locking mechanics, see the <a href="recursive_mutex.html">recursive
mutexes</a> supplied by <b>Boost.Threads</b>.</p>
<p>Each class supplies one or more typedefs for lock types which model matching
lock concepts. For the best possible performance you should use the mutex class
that supports the minimum set of lock types that you need.</p>
<table summary="lock types" border="1" cellpadding="5">
<tr>
<td><b>Mutex Class</b></td>
<td><b>Lock name</b></td>
<td><b>Lock Concept</b></td>
</tr>
<tr>
<td valign="top"><a href="#mutex Synopsis"><code> mutex</code></a></td>
<td valign="middle"><code>scoped_lock</code></td>
<td valign="middle"><a href="lock_concept.html#ScopedLock"> ScopedLock</a></td>
</tr>
<tr>
<td valign="top"><code><a href="#try_mutex Synopsis"> try_mutex</a></code>
</td>
<td valign="middle"><code>scoped_lock<br>
scoped_try_lock</code></td>
<td valign="middle"><a href="lock_concept.html#ScopedLock"> ScopedLock</a><br>
<a href="lock_concept.html#ScopedTryLock"> ScopedTryLock</a></td>
</tr>
<tr>
<td valign="top"><code><a href="#timed_mutex Synopsis"> timed_mutex</a></code>
</td>
<td valign="middle"><code>scoped_lock<br>
scoped_try_lock<br>
scoped_timed_lock</code></td>
<td valign="middle"><a href="lock_concept.html#ScopedLock"> ScopedLock</a><br>
<a href="lock_concept.html#ScopedTryLock"> ScopedTryLock</a><br>
<a href="lock_concept.html#ScopedTimedLock"> ScopedTimedLock</a></td>
</tr>
</table>
<p>The <code>mutex</code>, <code>try_mutex</code> and <code>timed_mutex</code>
classes use an <code>Unspecified</code> <a href="mutex_concept.html#LockingStrategies">locking
strategy</a>, so attempts to recursively lock them or attempts to unlock them
by threads that don&#39;t own a lock on them result in <b>undefined behavior</b>.
This strategy allows implementations to be as efficient as possible on any given
platform. It is, however, recommended that implementations include debugging
support to detect misuse when <code>NDEBUG</code> is not defined.</p>
<p>Like all the <b>Boost.Threads</b> <a href="mutex_concept.html">mutex models</a>,
the <code>mutex</code>, <code>try_mutex</code> and <code> timed_mutex</code>
leave the <a href="mutex_concept.html#SchedulingPolicies">scheduling policy</a>
as <code> Unspecified</code>. Programmers should make no assumptions about the
order in which waiting threads acquire a lock.</p>
<h2><a name="classes"></a>Classes</h2>
<h3><a name="class-mutex"></a>Class <code>mutex</code></h3>
<p>The <code>mutex</code> class is a model of <a href="mutex_concept.html#Mutex-concept">Mutex</a>
and <a href="overview.html#non-copyable">NonCopyable</a>, and provides no additional
facilities beyond the requirements of these concepts.</p>
<h4><a name="class-mutex-synopsis"></a>Class <code>mutex</code> synopsis</h4>
<pre>
namespace boost
{
class mutex : private <a href="../../utility/utility.htm">boost::noncopyable</a> // Exposition only.
// Class mutex meets the <a href="overview.html#non-copyable">NonCopyable</a> requirement.
{
public:
typedef <i>[implementation defined; see <a href="#Introduction">Introduction</a>]</i> scoped_lock;
mutex();
~mutex();
};
};
</pre>
<h4><a name="class-mutex-ctors"></a>Class <code>mutex</code> constructors and
destructor</h4>
<pre>
mutex();
</pre>
<dl class="function-semantics">
<dt><b>Postconditions:</b> <code>*this</code> is in an unlocked state.</dt>
</dl>
<pre>
~mutex();
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> <code>*this</code> is in an unlocked sate.</dt>
<dt><b>Danger:</b> Destruction of a locked mutex is a serious programming error
resulting in undefined behavior such as a program crash.</dt>
</dl>
<h3><a name="class-try_mutex"></a>Class <code>try_mutex</code></h3>
<p>The <code>try_mutex</code> class is a model of <a href="mutex_concept.html#TryMutex-concept">TryMutex</a>
and <a href="overview.html#non-copyable">NonCopyable</a>, and provides no additional
facilities beyond the requirements of these concepts.</p>
<h4><a name="class-try_mutex-synopsis"></a>Class <code>try_mutex</code> synopsis</h4>
<pre>
namespace boost
{
class try_mutex : private <a href="../../utility/utility.htm">boost::noncopyable</a> // Exposition only.
// Class try_mutex meets the <a href="overview.html#non-copyable">NonCopyable</a> requirement.
{
Public:
typedef <i>[implementation defined; see <a href="#Introduction">Introduction</a>]</i> scoped_lock;
typedef <i>[implementation defined; see <a href="#Introduction">Introduction</a>]</i> scoped_try_lock;
try_mutex();
~try_mutex();
};
};
</pre>
<h4><a name="class-try_mutex-ctors"></a>Class <code>try_mutex</code> constructors
and destructor</h4>
<pre>
try_mutex();
</pre>
<dl class="function-semantics">
<dt><b>Postconditions:</b> <code>*this</code> is in an unlocked state.</dt>
</dl>
<pre>
~try_mutex();
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> <code>*this</code> is in an unlocked sate.</dt>
<dt><b>Danger:</b> Destruction of a locked mutex is a serious programming error
resulting in undefined behavior such as a program crash.</dt>
</dl>
<h3><a name="class-timed_mutex"></a>Class <code>timed_mutex</code></h3>
<p>The <code>timed_mutex</code> class is a model of <a href="mutex_concept.html#TimedMutex-concept">TimedMutex</a>
and <a href="overview.html#non-copyable">NonCopyable</a>, and provides no additional
facilities beyond the requirements of these concepts.</p>
<h4><a name="class-timed_mutex-synopsis"></a>Class <code>timed_mutex</code> synopsis</h4>
<pre>
namespace boost
{
class timed_mutex : private <a href="../../utility/utility.htm">boost::noncopyable</a> // Exposition only.
// Class timed_mutex meets the <a href="overview.html#non-copyable">NonCopyable</a> requirement.
{
Public:
typedef <i>[implementation defined; see <a href="#Introduction">Introduction</a>]</i> scoped_lock;
typedef <i>[implementation defined; see <a href="#Introduction">Introduction</a>]</i> scoped_try_lock;
typedef <i>[implementation defined; see <a href="#Introduction">Introduction</a>]</i> scoped_timed_lock;
timed_mutex();
~timed_mutex();
};
};
</pre>
<h4><a name="class-timed_mutex-ctors"></a>Class <code>timed_mutex</code> constructors
and destructor</h4>
<pre>
timed_mutex();
</pre>
<dl class="function-semantics">
<dt><b>Postconditions:</b> <code>*this</code> is in an unlocked state.</dt>
</dl>
<pre>
~timed_mutex();
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> <code>*this</code> is in an unlocked sate.</dt>
<dt><b>Danger:</b> Destruction of a locked mutex is a serious programming error
resulting in undefined behavior such as a program crash.</dt>
</dl>
<h2><a name="examples"></a>Example(s)</h2>
<p><a href="../example/mutex.cpp">libs/thread/example/mutex.cpp</a></p>
<p>The output is:</p>
<pre>
count == 1
count == 2
count == 3
count == 4
</pre>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

239
doc/mutex_concept.html Normal file
View File

@@ -0,0 +1,239 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Mutex Concept</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300"> <a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Mutex Concept</h2>
</td>
</tr>
</table>
<hr>
<dl class="page-index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#locking-strategies">Locking Strategies</a></dt>
<dl class="page-index">
<dt><a href="#locking-strategy-recursive">Recursive</a></dt>
<dt><a href="#locking-strategy-checked">Checked</a></dt>
<dt><a href="#locking-strategy-unchecked">Unchecked</a></dt>
<dt><a href="#locking-strategy-unspecified">Unspecified</a></dt>
</dl>
<dt><a href="#scheduling-policies">Scheduling Policies</a></dt>
<dl class="page-index">
<dt><a href="#scheduling-policy-FIFO">FIFO</a></dt>
<dt><a href="#scheduling-policy-priority-driven">Priority Driven</a></dt>
<dt><a href="#scheduling-policy-unspecified">Unspecified</a></dt>
</dl>
<dt><a href="#concept-requirements">Concept Requirements</a></dt>
<dl class="page-index">
<dt><a href="#Mutex-concept">Mutex Concept</a></dt>
<dt><a href="#TryMutex-concept">TryMutex Concept</a></dt>
<dt><a href="#TimedMutex-concept">TimedMutex Concept</a></dt>
</dl>
<dt><a href="#models">Models</a></dt>
</dl>
<h2><a name="introduction"></a>Introduction</h2>
<p>A mutex (short for mutual-exclusion) object is used to serializes access to
a resource shared between multiple threads. The <a href="#Mutex">Mutex</a> concept,
with <a href="#TryMutex">TryMutex</a> and <a href="#TimedMutex">TimedMutex</a>
refinements, formalize the requirements. A model that implements Mutex and its
refinements has two states: <b>locked</b> and <b>unlocked</b>. Before using
a shared resource, a thread locks a <b>Boost.Threads</b> mutex object (an object
whose type is a model of <a href="#Mutex-concept">Mutex</a> or one of it's
refinements), insuring <a href="definitions.html#thread-safe">thread-safe</a>
access to the shared resource. When use of the shared resource is complete,
the thread unlocks the mutex object, allowing another thread to acquire the
lock and use the shared resource.</p>
<p>Traditional C thread APIs, like POSIX threads or the Windows thread APIs, expose
functions to lock and unlock a mutex object. This is dangerous since it&#39;s
easy to forget to unlock a locked mutex. When the flow of control is complex,
with multiple return points, the likelihood of forgetting to unlock a mutex
object would become even greater. When exceptions are thrown, it becomes nearly
impossible to ensure that the mutex object is unlocked properly when using these
traditional API&#39;s. The result is <a href="definitions.html#deadlock">deadlock</a>.</p>
<p>Many C++ threading libraries use a pattern known as <i>Scoped Locking</i> <a href="bibliography.html#Schmidt-00">[Schmidt
00]</a> to free the programmer from the need to explicitly lock and unlock mutex
objects. With this pattern, a <a href="lock_concept.html">Lock</a> concept is
employed where the lock object&#39;s constructor locks the associated mutex
object and the destructor automatically does the unlocking. The <b>Boost.Threads</b>
library takes this pattern to the extreme in that Lock concepts are the only
way to lock and unlock a mutex object: lock and unlock functions are not exposed
by any <b>Boost.Threads</b> mutex objects. This helps to ensure safe usage patterns,
especially when code throws exceptions.</p>
<h2><a name="locking-strategies"></a>Locking Strategies</h2>
<p>Every mutex object follows one of several locking strategies. These strategies
define the semantics for the locking operation when the calling thread already
owns a lock on the mutex object.</p>
<h3><a name="locking-strategy-recursive"></a>Recursive</h3>
<p>With a recursive locking strategy when a thread attempts to acquire a lock
on the mutex object for which it already owns a lock, the operation is successful.
Note the distinction between a thread, which may have multiple locks outstanding
on a recursive mutex object, and a lock object, which even for a recursive mutex
object cannot have any of its lock functions called multiple times without first
calling unlock.</p>
<p>Internally a lock count is maintained and the owning thread must unlock the
mutex model the same number of times that it&#39;s locked it before the mutex
object&#39;s state returns to unlocked. Since mutex objects in <b>Boost.Threads</b>
expose locking functionality only through lock concepts, a thread will always
unlock a mutex object the same number of times that it locked it. This helps
to eliminate a whole set of errors typically found in traditional C style thread
APIs.</p>
<p>Classes <a href="recursive_mutex.html#class-recursive_mutex">recursive_mutex</a>,
<a href="recursive_mutex.html#class-recursive_try_mutex">recursive_try_mutex</a>
and <a href="recursive_mutex.html#class-recursive_timed_mutex">recursive_timed_mutex</a>
use this locking strategy.</p>
<h3><a name="locking-strategy-checked"></a>Checked</h3>
<p>With a checked locking strategy when a thread attempts to acquire a lock on
the mutex object for which the thread already owns a lock, the operation will
fail with some sort of error indication. Further, attempts by a thread to unlock
a mutex object that was not locked by the thread will also return some sort
of error indication. In <b>Boost.Threads</b>, an exception of type <a href="exceptions.html#class-lock_error">
lock_error</a> would be thrown in these cases.</p>
<p><b>Boost.Threads</b> does not currently provide any mutex objects that use
this strategy.</p>
<h3><a name="locking-strategy-unchecked"></a>Unchecked</h3>
<p>With an unchecked locking strategy when a thread attempts to acquire a lock
on a mutex object for which the thread already owns a lock the operation will
<a href="definitions.html#definition-deadlock">deadlock</a>. In general this
locking strategy is less safe than a checked or recursive strategy, but it&#39;s
also a faster strategy and so is employed by many libraries.</p>
<p><b>Boost.Threads</b> does not currently provide any mutex objects that use
this strategy.</p>
<h3><a name="locking-strategy-unspecified"></a>Unspecified</h3>
<p>With an unspecified locking strategy, when a thread attempts to acquire a lock
on a mutex object for which the thread already owns a lock the operation results
in <b>undefined behavior</b>.</p>
<p>In general a mutex object with an unspecified locking strategy is unsafe, and
it requires programmer discipline to use the mutex object properly. However,
this strategy allows an implementation to be as fast as possible with no restrictions
on its implementation. This is especially true for portable implementations
that wrap the native threading support of a platform. For this reason, the classes
<a href="mutex.html#class-mutex">mutex</a>, <a href="mutex.html#class-try_mutex">try_mutex</a>
and <a href="mutex.html#class-timed_mutex">timed_mutex</a> use this locking
strategy despite the lack of safety.</p>
<h2><a name="scheduling-policies"></a>Scheduling Policies</h2>
<p>Every mutex object follows one of several scheduling policies. These policies
define the semantics when the mutex object is unlocked and there is more than
one thread waiting to acquire a lock. In other words, the policy defines which
waiting thread shall acquire the lock.</p>
<h3><a name="scheduling-policy-FIFO"></a>FIFO</h3>
<p>With a FIFO scheduling policy, threads waiting for the lock will acquire it
in a first come first serve order (or First In First Out). This can help prevent
a high priority thread from starving lower priority threads that are also waiting
on the mutex object's lock.</p>
<h3><a name="scheduling-policy-priority-driven"></a>Priority Driven</h3>
<p>With a Priority Driven scheduling policy, the thread with the highest priority
acquires the lock. Note that this means that low-priority threads may never
acquire the lock if the mutex object has high contention and there is always
at least one high-priority thread waiting. This is known as thread starvation.
When multiple threads of the same priority are waiting on the mutex object's
lock one of the other scheduling priorities will determine which thread shall
acquire the lock.</p>
<h3><a name="scheduling-policy-unspecified"></a>Unspecified</h3>
<p>The mutex object does not specify a scheduling policy. In order to ensure portability,
all <b>Boost.Threads</b> mutex models use an unspecified scheduling policy.</p>
<h2><a name="concept-requirements"></a>Concept Requirements</h2>
<h3><a name="Mutex-concept"></a>Mutex Concept</h3>
<p>A Mutex object has two states: locked and unlocked. Mutex object state can
only be determined by an object meeting the <a href="lock_concept.html#ScopedLock">ScopedLock</a>
requirements and constructed for the Mutex object.</p>
<p>A Mutex is <a href="../../utility/utility.htm#Class noncopyable">NonCopyable</a>.</p>
<p>For a Mutex type M and an object m of that type, the following expressions
must be well-formed and have the indicated effects.</p>
<table summary="Mutex expressions" border="1" cellpadding="5">
<tr>
<td><b>Expression</b></td>
<td><b>Effects</b></td>
</tr>
<tr>
<td><code>M m;</code></td>
<td>Constructs a mutex object m. Post-condition: m is unlocked.</td>
</tr>
<tr>
<td><code>(&amp;m)-&gt;~M();</code></td>
<td>Precondition: m is unlocked. Destroys a mutex object m.</td>
</tr>
<tr>
<td><code>M::scoped_lock</code></td>
<td>A model of <a href="lock_concept.html#ScopedLock">ScopedLock</a>.</td>
</tr>
</table>
<h3><a name="TryMutex-concept"></a>TryMutex Concept</h3>
<p>A TryMutex is a refinement of <a href="#Mutex-concept">Mutex</a>. For a TryMutex
type M and an object m of that type, the following expressions must be well-formed
and have the indicated effects.</p>
<table summary="TryMutex expressions" border="1" cellpadding="5">
<tr>
<td><b>Expression</b></td>
<td><b>Effects</b></td>
</tr>
<tr>
<td><code>M::scoped_try_lock</code></td>
<td>A model of <a href="lock_concept.html#ScopedTryLock">ScopedTryLock</a>.</td>
</tr>
</table>
<h3><a name="TimedMutex-concept"></a>TimedMutex Concept</h3>
<p>A TimedMutex is a refinement of <a href="#TryMutex-concept">TryMutex</a>. For
a TimedMutex type M and an object m of that type, the following expressions
must be well-formed and have the indicated effects.</p>
<table summary="TimedMutex expressions" border="1" cellpadding="5">
<tr>
<td><b>Expression</b></td>
<td><b>Effects</b></td>
</tr>
<tr>
<td><code>M::scoped_timed_lock</code></td>
<td>A model of <a href="lock_concept.html#ScopedTimedLock">ScopedTimedLock</a>.</td>
</tr>
</table>
<h2><a name="models"></a>Models</h2>
<p><b>Boost.Threads</b> currently supplies six models of Mutex.</p>
<table summary="Mutex concept classes" border="1" cellpadding="5">
<tr>
<td><b>Concept</b></td>
<td><b>Refines</b></td>
<td><b>Models</b></td>
</tr>
<tr>
<td valign="top"><a href="#Mutex-concept">Mutex</a></td>
<td valign="top">&nbsp;</td>
<td><a href="mutex.html">mutex</a><br>
<a href="recursive_mutex.html">recursive_mutex</a></td>
</tr>
<tr>
<td valign="top"><a href="#TryMutex-concept">TryMutex</a></td>
<td valign="top"><a href="#Mutex-concept">Mutex</a></td>
<td><a href="mutex.html">try_mutex<br>
</a> <a href="recursive_mutex.html">recursive_try_mutex</a> </td>
</tr>
<tr>
<td valign="top"><a href="#TimedMutex-concept">TimedMutex</a></td>
<td valign="top"><a href="#TryMutex-concept">TryMutex</a></td>
<td><a href="mutex.html">timed_mutex<br>
</a> <a href="recursive_mutex.html"> recursive_timed_mutex</a></td>
</tr>
</table>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -1,224 +0,0 @@
[/
(C) Copyright 2007-8 Anthony Williams.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
]
[section:mutex_types Mutex Types]
[section:mutex Class `mutex`]
#include <boost/thread/mutex.hpp>
class mutex:
boost::noncopyable
{
public:
mutex();
~mutex();
void lock();
bool try_lock();
void unlock();
typedef platform-specific-type native_handle_type;
native_handle_type native_handle();
typedef unique_lock<mutex> scoped_lock;
typedef unspecified-type scoped_try_lock;
};
__mutex__ implements the __lockable_concept__ to provide an exclusive-ownership mutex. At most one thread can own the lock on a given
instance of __mutex__ at any time. Multiple concurrent calls to __lock_ref__, __try_lock_ref__ and __unlock_ref__ shall be permitted.
[section:nativehandle Member function `native_handle()`]
typedef platform-specific-type native_handle_type;
native_handle_type native_handle();
[variablelist
[[Effects:] [Returns an instance of `native_handle_type` that can be used with platform-specific APIs to manipulate the underlying
implementation. If no such instance exists, `native_handle()` and `native_handle_type` are not present.]]
[[Throws:] [Nothing.]]
]
[endsect]
[endsect]
[section:try_mutex Typedef `try_mutex`]
#include <boost/thread/mutex.hpp>
typedef mutex try_mutex;
__try_mutex__ is a `typedef` to __mutex__, provided for backwards compatibility with previous releases of boost.
[endsect]
[section:timed_mutex Class `timed_mutex`]
#include <boost/thread/mutex.hpp>
class timed_mutex:
boost::noncopyable
{
public:
timed_mutex();
~timed_mutex();
void lock();
void unlock();
bool try_lock();
bool timed_lock(system_time const & abs_time);
template<typename TimeDuration>
bool timed_lock(TimeDuration const & relative_time);
typedef platform-specific-type native_handle_type;
native_handle_type native_handle();
typedef unique_lock<timed_mutex> scoped_timed_lock;
typedef unspecified-type scoped_try_lock;
typedef scoped_timed_lock scoped_lock;
};
__timed_mutex__ implements the __timed_lockable_concept__ to provide an exclusive-ownership mutex. At most one thread can own the
lock on a given instance of __timed_mutex__ at any time. Multiple concurrent calls to __lock_ref__, __try_lock_ref__,
__timed_lock_ref__, __timed_lock_duration_ref__ and __unlock_ref__ shall be permitted.
[section:nativehandle Member function `native_handle()`]
typedef platform-specific-type native_handle_type;
native_handle_type native_handle();
[variablelist
[[Effects:] [Returns an instance of `native_handle_type` that can be used with platform-specific APIs to manipulate the underlying
implementation. If no such instance exists, `native_handle()` and `native_handle_type` are not present.]]
[[Throws:] [Nothing.]]
]
[endsect]
[endsect]
[section:recursive_mutex Class `recursive_mutex`]
#include <boost/thread/recursive_mutex.hpp>
class recursive_mutex:
boost::noncopyable
{
public:
recursive_mutex();
~recursive_mutex();
void lock();
bool try_lock();
void unlock();
typedef platform-specific-type native_handle_type;
native_handle_type native_handle();
typedef unique_lock<recursive_mutex> scoped_lock;
typedef unspecified-type scoped_try_lock;
};
__recursive_mutex__ implements the __lockable_concept__ to provide an exclusive-ownership recursive mutex. At most one thread can
own the lock on a given instance of __recursive_mutex__ at any time. Multiple concurrent calls to __lock_ref__, __try_lock_ref__ and
__unlock_ref__ shall be permitted. A thread that already has exclusive ownership of a given __recursive_mutex__ instance can call
__lock_ref__ or __try_lock_ref__ to acquire an additional level of ownership of the mutex. __unlock_ref__ must be called once for
each level of ownership acquired by a single thread before ownership can be acquired by another thread.
[section:nativehandle Member function `native_handle()`]
typedef platform-specific-type native_handle_type;
native_handle_type native_handle();
[variablelist
[[Effects:] [Returns an instance of `native_handle_type` that can be used with platform-specific APIs to manipulate the underlying
implementation. If no such instance exists, `native_handle()` and `native_handle_type` are not present.]]
[[Throws:] [Nothing.]]
]
[endsect]
[endsect]
[section:recursive_try_mutex Typedef `recursive_try_mutex`]
#include <boost/thread/recursive_mutex.hpp>
typedef recursive_mutex recursive_try_mutex;
__recursive_try_mutex__ is a `typedef` to __recursive_mutex__, provided for backwards compatibility with previous releases of boost.
[endsect]
[section:recursive_timed_mutex Class `recursive_timed_mutex`]
#include <boost/thread/recursive_mutex.hpp>
class recursive_timed_mutex:
boost::noncopyable
{
public:
recursive_timed_mutex();
~recursive_timed_mutex();
void lock();
bool try_lock();
void unlock();
bool timed_lock(system_time const & abs_time);
template<typename TimeDuration>
bool timed_lock(TimeDuration const & relative_time);
typedef platform-specific-type native_handle_type;
native_handle_type native_handle();
typedef unique_lock<recursive_timed_mutex> scoped_lock;
typedef unspecified-type scoped_try_lock;
typedef scoped_lock scoped_timed_lock;
};
__recursive_timed_mutex__ implements the __timed_lockable_concept__ to provide an exclusive-ownership recursive mutex. At most one
thread can own the lock on a given instance of __recursive_timed_mutex__ at any time. Multiple concurrent calls to __lock_ref__,
__try_lock_ref__, __timed_lock_ref__, __timed_lock_duration_ref__ and __unlock_ref__ shall be permitted. A thread that already has
exclusive ownership of a given __recursive_timed_mutex__ instance can call __lock_ref__, __timed_lock_ref__,
__timed_lock_duration_ref__ or __try_lock_ref__ to acquire an additional level of ownership of the mutex. __unlock_ref__ must be
called once for each level of ownership acquired by a single thread before ownership can be acquired by another thread.
[section:nativehandle Member function `native_handle()`]
typedef platform-specific-type native_handle_type;
native_handle_type native_handle();
[variablelist
[[Effects:] [Returns an instance of `native_handle_type` that can be used with platform-specific APIs to manipulate the underlying
implementation. If no such instance exists, `native_handle()` and `native_handle_type` are not present.]]
[[Throws:] [Nothing.]]
]
[endsect]
[endsect]
[include shared_mutex_ref.qbk]
[endsect]

90
doc/once.html Normal file
View File

@@ -0,0 +1,90 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Header &lt;boost/thread/once.hpp&gt;</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Header &lt;<a href="../../../boost/thread/once.hpp">boost/thread/once.hpp</a>&gt;</h2>
</td>
</tr>
</table>
<hr>
<h2>Contents</h2>
<dl class="page-index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#macros">Macros</a></dt>
<dl class="page-index">
<dt><a href="#macro-BOOST_ONCE_INIT">BOOST_ONCE_INIT</a></dt>
</dl>
<dt><a href="#types">Types</a></dt>
<dl class="page-index">
<dt><a href="#type-once_flag">once_flag</a></dt>
</dl>
<dt><a href="#functions">Functions</a></dt>
<dl class="page-index">
<dt><a href="#function-call_once">call_once</a></dt>
</dl>
<dt><a href="#examples">Example(s)</a></dt>
</dl>
<hr>
<h2><a name="introduction"></a>Introduction</h2>
<p>Include the header &lt;<a href="../../../boost/thread/once.hpp">boost/thread/once.hpp</a>&gt;
to define the <code>call_once</code> function, <code>once_flag</code> type and
<code>BOOST_ONCE_INIT</code> constant.</p>
<p>The <code>call_once</code> function and <code>once_flag</code> type (statically
initialized to <code>BOOST_ONCE_INIT</code>) can be used to run a routine exactly
once. This can be used to initialize data in a <a href="definitions.html#Thread-safe">
thread-safe</a> manner.</p>
<h2><a name="macros"></a>Macros</h2>
<pre>
<a name="macro-BOOST_ONCE_INIT"></a>#define BOOST_ONCE_INIT <i>implementation defined</i>
</pre>
<p>This is a constant value used to initialize <code>once_flag</code> instances
to indicate that the logically associated routine has not been run yet.</p>
<h2><a name="types"></a>Types</h2>
<pre>
<a name="type-once_flag"></a>typedef <i>implementation defined</i> once_flag;
</pre>
<p>This implementation defined type is used as a flag to insure a routine is called
only once. Instances of this type should be statically initialized to <code>BOOST_ONCE_INIT</code>.</p>
<h2><a name="functions"></a>Functions</h2>
<pre>
<a name="function-call_once"></a>void call_once(void (*func)(), once_flag& flag);
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> The function <code>func</code> shall not throw exceptions.</dt>
<dt><b>Effects:</b> As if (in an atomic fashion):
<pre>
if (flag == BOOST_ONCE_INIT)
func();
</pre>
</dt>
<dt><b>Postconditions:</b> <code>flag != BOOST_ONCE_INIT</code></dt>
</dl>
<h2><a name="examples"></a>Example(s)</h2>
<p><a href="../example/once.cpp">libs/thread/example/once.cpp</a></p>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

View File

@@ -1,65 +0,0 @@
[/
(C) Copyright 2007-8 Anthony Williams.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
]
[section:once One-time Initialization]
`boost::call_once` provides a mechanism for ensuring that an initialization routine is run exactly once without data races or deadlocks.
[section:once_flag Typedef `once_flag`]
#include <boost/thread/once.hpp>
typedef platform-specific-type once_flag;
#define BOOST_ONCE_INIT platform-specific-initializer
Objects of type `boost::once_flag` shall be initialized with `BOOST_ONCE_INIT`:
boost::once_flag f=BOOST_ONCE_INIT;
[endsect]
[section:call_once Non-member function `call_once`]
#include <boost/thread/once.hpp>
template<typename Callable>
void call_once(once_flag& flag,Callable func);
[variablelist
[[Requires:] [`Callable` is `CopyConstructible`. Copying `func` shall have no side effects, and the effect of calling the copy shall
be equivalent to calling the original. ]]
[[Effects:] [Calls to `call_once` on the same `once_flag` object are serialized. If there has been no prior effective `call_once` on
the same `once_flag` object, the argument `func` (or a copy thereof) is called as-if by invoking `func()`, and the invocation of
`call_once` is effective if and only if `func()` returns without exception. If an exception is thrown, the exception is
propagated to the caller. If there has been a prior effective `call_once` on the same `once_flag` object, the `call_once` returns
without invoking `func`. ]]
[[Synchronization:] [The completion of an effective `call_once` invocation on a `once_flag` object, synchronizes with
all subsequent `call_once` invocations on the same `once_flag` object. ]]
[[Throws:] [`thread_resource_error` when the effects cannot be achieved. or any exception propagated from `func`.]]
[[Note:] [The function passed to `call_once` must not also call
`call_once` passing the same `once_flag` object. This may cause
deadlock, or invoking the passed function a second time. The
alternative is to allow the second call to return immediately, but
that assumes the code knows it has been called recursively, and can
proceed even though the call to `call_once` didn't actually call the
function, in which case it could also avoid calling `call_once`
recursively.]]
]
void call_once(void (*func)(),once_flag& flag);
This second overload is provided for backwards compatibility. The effects of `call_once(func,flag)` shall be the same as those of
`call_once(flag,func)`.
[endsect]
[endsect]

173
doc/overview.html Normal file
View File

@@ -0,0 +1,173 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Overview</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Overview</h2>
</td>
</tr>
</table>
<hr>
<dl class="index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#dangers">Dangers</a></dt>
<dl class="index">
<dt><a href="#testing-debugging">Testing and debugging considerations</a></dt>
<dt><a href="#head-start">Getting a head start</a></dt>
</dl>
<dt><a href="#library">C++ Standard Library usage in multithreaded programs</a></dt>
<dl class="index">
<dt><a href="#runtime-libraries">Runtime libraries</a></dt>
<dt><a href="#non-thread-safe-functions">Potentially non-thread-safe functions</a></dt>
</dl>
<dt><a href="#common-requirements">Common requirements for all Boost.Threads
components</a></dt>
<dl class="index">
<dt><a href="#exceptions">Exceptions</a></dt>
<dt><a href="#non-copyable">NonCopyable requirement</a></dt>
</dl>
</dl>
<h2><a name="introduction"></a>Introduction</h2>
<p>Boost.Threads allows C++ programs to execute as multiple, asynchronous, independent,
threads-of-execution. Each thread has its own machine state including program
instruction counter and registers. Programs which execute as multiple threads
are called multithreaded programs to distinguish them from traditional single-threaded
programs. <a href="definitions.html">Definitions</a> gives a more complete description
of the multithreading execution environment.</p>
<p>Multithreading provides several advantages:</p>
<ul>
<li>Programs which would otherwise block waiting for some external event can
continue to respond if the blocking operation is placed in a separate thread.
Multithreading is usually an absolute requirement for these programs.</li>
</ul>
<ul>
<li>Well-designed multithreaded programs may execute faster than single-threaded
programs, particularly on multiprocessor hardware. Note, however, that poorly-designed
multithreaded programs are often slower that single-threaded programs.</li>
</ul>
<ul>
<li>Some program designs may be easier to formulate using a multithreaded approach.
After all, the real world is asynchronous!</li>
</ul>
<h2><a name="dangers"></a>Dangers</h2>
<p>Beyond the errors which can occur in single-threaded programs, multithreaded
programs are subject to additional errors:</p>
<ul>
<li><a href="definitions.html#definition-race-condition">Race conditions</a>.</li>
<li><a href="definitions.html#definition-deadlock">Deadlock</a> (sometimes called
&quot;deadly embrace&quot;)</li>
<li><a href="definitions.html#definition-priority-failure">Priority failures</a>
(priority inversion, infinite overtaking, starvation, etc.)</li>
</ul>
<p>Every multithreaded program must be designed carefully to avoid race conditions,
priority failures and deadlock. These aren&#39;t rare or exotic failures - they
are virtually guaranteed to occur unless multithreaded code is designed to avoid
them. Priority failures are somewhat less common, but are nonetheless serious.</p>
<p>The <a href="introduction.html">Boost.Threads design</a> attempts to minimize
these errors, but they will still occur unless the programmer proactively designs
to avoid them.</p>
<h3><a name="testing-debugging"></a>Testing and debugging considerations</h3>
<p>Multithreaded programs are non-deterministic. In other words, the same program
with the same input data may follow different execution paths each time it is
invoked. That can make testing and debugging a nightmare:</p>
<ul>
<li>Failures are often not repeatable.</li>
<li>Probe effect causes debuggers to produce very different results from non-debug
uses.</li>
<li>Debuggers require special support to show thread state.</li>
<li>Tests on a single processor system may give no indication of serious errors
which would appear on multiprocessor systems, and visa versa. Thus test cases
should include a varying number of processors.</li>
<li>For programs which create a varying number of threads according to workload,
tests which don&#39;t span the full range of possibilities may miss serious
errors.</li>
</ul>
<h3><a name="head-start"></a>Getting a head start</h3>
<p>Although it might appear that multithreaded programs are inherently unreliable,
many reliable multithreaded programs do exist. Multithreading techniques are
known which lead to reliable programs.</p>
<p>Design patterns for reliable multithreaded programs, including the important
<i>monitor</i> pattern, are presented in <cite> Pattern-Oriented Software Architecture
Volume 2 - Patterns for Concurrent and Networked Objects</cite> [<a href=
"bibliography.html#Schmidt-00">Schmidt 00</a>]. Many important multithreading
programming considerations (independent of threading library) are discussed
in <cite>Programming with POSIX Threads</cite> [<a href="bibliography.html#Butenhof-97">Butenhof
97</a>].</p>
<p>Doing some reading before attempting multithreaded designs will give you a
head start toward reliable multithreaded programs.</p>
<h2><a name="library"></a>C++ Standard Library usage in multithreaded programs</h2>
<h3><a name="runtime-libraries"></a>Runtime libraries</h3>
<p><b>Warning:</b> Multithreaded programs such as those using <b> Boost.Threads</b>
must link to <a href="definitions.html#Thread-safe"> thread-safe</a> versions
of all runtime libraries used by the program, including the runtime library
for the C++ Standard Library. Otherwise <a href="definitions.html#Race condition">race
conditions</a> will occur when multiple threads simultaneously execute runtime
library functions for <i>new</i>, <i>delete</i>, or other language features
which imply shared state.</p>
<h3><a name="non-thread-safe-functions"></a>Potentially non-thread-safe functions</h3>
<p>Certain C++ Standard Library functions inherited from C are particular problems
because they hold internal state between calls:</p>
<ul>
<li>rand</li>
<li>strtok</li>
<li>asctime</li>
<li>ctime</li>
<li>gmtime</li>
<li>localtime</li>
</ul>
<p>It is possible to write thread-safe implementations of these by using <a href="tss.html#class-thread_specific_ptr">thread-specific
storage</a>, and several C++ compiler vendors do just that. The technique is
well-know and is explained in [<a href=
"bibliography.html#Butenhof-97">Buttenhof 97</a>].</p>
<p>But at least one vendor (HP-UX) does not provide thread-safe implementations
of the above functions in their otherwise thread-safe runtime library. Instead
they provide replacement functions with different names and arguments.</p>
<p><b>Recommendation:</b> For the most portable, yet thread-safe code, use Boost
replacements for the problem functions. See the <a href=
"../../random/index.html">Boost Random Number Library</a> and <a href=
"../../tokenizer/index.htm">Boost Tokenizer Library</a>.</p>
<h2><a name="common-gaurantees"></a>Common guarantees for all Boost.Threads components</h2>
<h3><a name="exceptions"></a>Exceptions</h3>
<p><b>Boost.Threads</b> destructors never throw exceptions. Unless otherwise specified,
other <b>Boost.Threads</b> functions that do not have an exception-specification
may throw implementation-defined exceptions.</p>
<p>In particular, <b>Boost.Threads</b> reports failure to allocate storage by
throwing an exception of type std::bad_alloc, or a class derived from std::bad_alloc,
failure to obtain thread resources other than memory by throwing an exception
of type <a href="exceptions.html#class-thread_resource_error">boost::thread_resource_error</a>,
and certain lock related failures by throwing an exception of type <a href="exceptions.html#class-lock_error">boost::lock_error</a></p>
<p><b>Rationale:</b> Follows the C++ Standard Library practice of allowing all
functions except destructors or other specified functions to throw exceptions
on errors.</p>
<h3><a name="non-copyable"></a>NonCopyable requirement</h3>
<p><b>Boost.Threads</b> classes documented as meeting the NonCopyable requirement
disallow copy construction and copy assignment. For the sake of exposition,
the synopsis of such classes show private derivation from <a href="../../utility/utility.htm">
boost::noncopyable</a>. Users should not depend on this derivation, however,
as implementations are free to meet the NonCopyable requirement in other ways.</p>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

View File

@@ -1,30 +0,0 @@
[/
(C) Copyright 2007-8 Anthony Williams.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
]
[section:overview Overview]
__boost_thread__ enables the use of multiple threads of execution with shared data in portable C++ code. It provides classes and
functions for managing the threads themselves, along with others for synchronizing data between the threads or providing separate
copies of data specific to individual threads.
The __boost_thread__ library was originally written and designed by William E. Kempf. This version is a major rewrite designed to
closely follow the proposals presented to the C++ Standards Committee, in particular
[@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2497.html N2497],
[@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2320.html N2320],
[@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2184.html N2184],
[@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2139.html N2139], and
[@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2094.html N2094]
In order to use the classes and functions described here, you can
either include the specific headers specified by the descriptions of
each class or function, or include the master thread library header:
#include <boost/thread.hpp>
which includes all the other headers in turn.
[endsect]

399
doc/rationale.html Normal file
View File

@@ -0,0 +1,399 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Rationale</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Rationale</h2>
</td>
</tr>
</table>
<hr>
<dl class="index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#library">Rationale for the Creation of <b>Boost.Threads</b></a></dt>
<dt><a href="#primitives">Rationale for the Low Level Primitives Supported in
<b>Boost.Threads</b></a></dt>
<dt><a href="#lock_objects">Rationale for the Lock Design</a></dt>
<dt><a href="#non-copyable">Rationale for NonCopyable Thread Type</a></dt>
<dt><a href="#events">Rationale for not providing <i>Event Variables</i></a></dt>
</dl>
<h2><a name="introduction"></a>Introduction</h2>
<p>This page explains the rationale behind various design decisions in the <b>Boost.Threads</b>
library. Having the rationale documented here should explain how we arrived
at the current design as well as prevent future rehashing of discussions and
thought processes that have already occurred. It can also give users a lot of
insight into the design process required for this library.</p>
<h2><a name="library"></a>Rationale for the Creation of <b>Boost.Threads</b></h2>
<p>Processes often have a degree of &quot;potential parallelism&quot; and it can
often be more intuitive to design systems with this in mind. Further, these
parallel processes can result in more responsive programs. The benefits for
multithreaded programming are quite well known to most modern programmers, yet
the C++ language doesn&#39;t directly support this concept.</p>
<p>Many platforms support multithreaded programming despite the fact that the
language doesn&#39;t support it. They do this through external libraries, which
are, unfortunately, platform specific. POSIX has tried to address this problem
through the standardization of a &quot;pthread&quot; library. However, this
is a standard only on POSIX platforms, so its portability is limited.</p>
<p>Another problem with POSIX and other platform specific thread libraries is
that they are almost universally C based libraries. This leaves several C++
specific issues unresolved, such as what happens when an exception is thrown
in a thread. Further, there are some C++ concepts, such as destructors, that
can make usage much easier than what&#39;s available in a C library.</p>
<p>What&#39;s truly needed is C++ language support for threads. However, the C++
standards committee needs existing practice or a good proposal as a starting
point for adding this to the standard.</p>
<p>The <b>Boost.Threads</b> library was developed to provide a C++ developer with
a portable interface for writing multithreaded programs on numerous platforms.
There&#39;s a hope that the library can be the basis for a more detailed proposal
for the C++ standards committee to consider for inclusion in the next C++ standard.</p>
<h2><a name="primitives"></a>Rationale for the Low Level Primitives Supported
in <b>Boost.Threads</b></h2>
<p>The <b>Boost.Threads</b> library supplies a set of low level primitives for
writing multithreaded programs, such as mutexes and condition variables. In
fact, the first release of <b>Boost.Threads</b> supports only these low level
primitives. However, computer science research has shown that use of these primitives
is difficult since it's difficult to mathematically prove that a usage pattern
is correct, meaning it doesn&#39;t result in race conditions or deadlocks. There
are several algebras (such as CSP, CCS and Join calculus) that have been developed
to help write provably correct parallel processes. In order to prove the correctness
these processes must be coded using higher level abstractions. So why does <b>Boost.Threads</b>
support the lower level concepts?</p>
<p>The reason is simple: the higher level concepts need to be implemented using
at least some of the lower level concepts. So having portable lower level concepts
makes it easier to develop the higher level concepts and will allow researchers
to experiment with various techniques.</p>
<p>Beyond this theoretical application of higher level concepts, however, the
fact remains that many multithreaded programs are written using only the lower
level concepts, so they are useful in and of themselves, even if it&#39;s hard
to prove that their usage is correct. Since many users will be familiar with
these lower level concepts but be unfamiliar with any of the higher level concepts
there&#39;s also an argument for accessibility.</p>
<h2><a name="lock_objects"></a>Rationale for the Lock Design</h2>
<p>Programmers who are used to multithreaded programming issues will quickly note
that the Boost.Thread&#39;s design for mutex lock concepts is not <a href="definitions.html#Thread-safe">thread-safe</a>
(this is clearly documented as well). At first this may seem like a serious
design flaw. Why have a multithreading primitive that&#39;s not thread-safe
itself?</p>
<p>A lock object is not a synchronization primitive. A lock object&#39;s sole
responsibility is to ensure that a mutex is both locked and unlocked in a manner
that won&#39;t result in the common error of locking a mutex and then forgetting
to unlock it. This means that instances of a lock object are only going to be
created, at least in theory, within block scope and won&#39;t be shared between
threads. Only the mutex objects will be created outside of block scope and/or
shared between threads. Though it&#39;s possible to create a lock object outside
of block scope and to share it between threads to do so would not be a typical
usage (in fact, to do so would likely be an error). Nor are there any cases
when such usage would be required.</p>
<p>Lock objects must maintain some state information. In order to allow a program
to determine if a try_lock or timed_lock was successful the lock object must
retain state indicating the success or failure of the call made in its constructor.
If a lock object were to have such state and remain thread-safe it would need
to synchronize access to the state information which would result in roughly
doubling the time of most operations. Worse, since checking the state can occur
only by a call after construction we&#39;d have a race condition if the lock
object were shared between threads.</p>
<p>So, to avoid the overhead of synchronizing access to the state information
and to avoid the race condition the <b>Boost.Threads</b> library simply does
nothing to make lock objects thread-safe. Instead, sharing a lock object between
threads results in undefined behavior. Since the only proper usage of lock objects
is within block scope this isn&#39;t a problem, and so long as the lock object
is properly used there&#39;s no danger of any multithreading issues.</p>
<h2><a name="non-copyable"></a>Rationale for NonCopyable Thread Type</h2>
<p>Programmers who are used to C libraries for multithreaded programming are likely
to wonder why <b>Boost.Threads</b> uses a noncopyable design for <a href="thread.html">boost::thread</a>.
After all, the C thread types are copyable, and you often have a need for copying
them within user code. However, careful comparison of C designs to C++ designs
shows a flaw in this logic.</p>
<p>All C types are copyable. It is, in fact, not possible to make a noncopyable
type in C. For this reason types that represent system resources in C are often
designed to behave very similarly to a pointer to dynamic memory. There&#39;s
an API for acquiring the resource and an API for releasing the resources. For
memory we have pointers as the type and alloc/free for the acquisition and release
APIs. For files we have FILE* as the type and fopen/fclose for the acquisition
and release APIs. You can freely copy instances of the types but must manually
manage the lifetime of the actual resource through the acquisition and release
APIs.</p>
<p>C++ designs recognize that the acquisition and release APIs are error prone
and try to eliminate possible errors by acquiring the resource in the constructor
and releasing it in the destructor. The best example of such a design is the
std::iostream set of classes which can represent the same resource as the FILE*
type in C. A file is opened in the std::fstream&#39;s constructor and closed
in its destructor. However, if an iostream were copyable it could lead to a
file being closed twice, an obvious error, so the std::iostream types are noncopyable
by design. This is the same design used by boost::thread, which is a simple
and easy to understand design that&#39;s consistent with other C++ standard
types.</p>
<p>During the design of boost::thread it was pointed out that it would be possible
to allow it to be a copyable type if some form of &quot;reference management&quot;
were used, such as ref-counting or ref-lists, and many argued for a boost::thread_ref
design instead. The reasoning was that copying &quot;thread&quot; objects was
a typical need in the C libraries, and so presumably would be in the C++ libraries
as well. It was also thought that implementations could provide more efficient
reference management than wrappers (such as boost::shared_ptr) around a noncopyable
thread concept. Analysis of whether or not these arguments would hold true doesn&#39;t
appear to bear them out. To illustrate the analysis we&#39;ll first provide
pseudo-code illustrating the six typical usage patterns of a thread object.</p>
<h3>1. Simple creation of a thread.</h3>
<pre>
void foo()
{
create_thread(&amp;bar);
}
</pre>
<h3>2. Creation of a thread that's later joined.</h3>
<pre>
Void foo()
{
thread = create_thread(&amp;bar);
join(thread);
}
</pre>
<h3>3. Simple creation of several threads in a loop.</h3>
<pre>
Void foo()
{
for (int i=0; i&lt;NUM_THREADS; ++i)
create_thread(&amp;bar);
}
</pre>
<h3>4. Creation of several threads in a loop which are later joined.</h3>
<pre>
Void foo()
{
for (int i=0; i&lt;NUM_THREADS; ++i)
threads[i] = create_thread(&amp;bar);
for (int i=0; i&lt;NUM_THREADS; ++i)
threads[i].join();
}
</pre>
<h3>5. Creation of a thread whose ownership is passed to another object/method.</h3>
<pre>
Void foo()
{
thread = create_thread(&amp;bar);
manager.owns(thread);
}
</pre>
<h3>6. Creation of a thread whose ownership is shared between multiple objects.</h3>
<pre>
Void foo()
{
thread = create_thread(&amp;bar);
manager1.add(thread);
manager2.add(thread);
}
</pre>
<p>Of these usage patterns there&#39;s only one that requires reference management
(number 6). Hopefully it&#39;s fairly obvious that this usage pattern simply
won&#39;t occur as often as the other usage patterns. So there really isn&#39;t
a &quot;typical need&quot; for a thread concept, though there is some need.</p>
<p>Since the need isn&#39;t typical we must use different criteria for deciding
on either a thread_ref or thread design. Possible criteria include ease of use
and performance. So let&#39;s analyze both of these carefully.</p>
<p>With ease of use we can look at existing experience. The standard C++ objects
that represent a system resource, such as std::iostream, are noncopyable, so
we know that C++ programmers must at least be experienced with this design.
Most C++ developers are also used to smart pointers such as boost::shared_ptr,
so we know they can at least adapt to a thread_ref concept with little effort.
So existing experience isn&#39;t going to lead us to a choice.</p>
<p>The other thing we can look at is how difficult it is to use both types for
the six usage patterns above. If we find it overly difficult to use a concept
for any of the usage patterns there would be a good argument for choosing the
other design. So we&#39;ll code all six usage patterns using both designs.</p>
<h3>1.</h3>
<pre>
void foo()
{
thread thrd(&amp;bar);
}
void foo()
{
thread_ref thrd = create_thread(&amp;bar);
}
</pre>
<h3>2.</h3>
<pre>
void foo()
{
thread thrd(&amp;bar);
thrd.join();
}
void foo()
{
thread_ref thrd =
create_thread(&amp;bar);thrd-&gt;join();
}
</pre>
<h3>3.</h3>
<pre>
void foo()
{
for (int i=0; i&lt;NUM_THREADS; ++i)
thread thrd(&amp;bar);
}
void foo()
{
for (int i=0; i&lt;NUM_THREADS; ++i)
thread_ref thrd = create_thread(&amp;bar);
}
</pre>
<h3>4.</h3>
<pre>
void foo()
{
std::auto_ptr&lt;thread&gt; threads[NUM_THREADS];
for (int i=0; i&lt;NUM_THREADS; ++i)
threads[i] = std::auto_ptr&lt;thread&gt;(new thread(&amp;bar));
for (int i= 0; i&lt;NUM_THREADS;
++i)threads[i]-&gt;join();
}
void foo()
{
thread_ref threads[NUM_THREADS];
for (int i=0; i&lt;NUM_THREADS; ++i)
threads[i] = create_thread(&amp;bar);
for (int i= 0; i&lt;NUM_THREADS;
++i)threads[i]-&gt;join();
}
</pre>
<h3>5.</h3>
<pre>
void foo()
{
thread thrd* = new thread(&amp;bar);
manager.owns(thread);
}
void foo()
{
thread_ref thrd = create_thread(&amp;bar);
manager.owns(thrd);
}
</pre>
<h3>6.</h3>
<pre>
void foo()
{
boost::shared_ptr&lt;thread&gt; thrd(new thread(&amp;bar));
manager1.add(thrd);
manager2.add(thrd);
}
void foo()
{
thread_ref thrd = create_thread(&amp;bar);
manager1.add(thrd);
manager2.add(thrd);
}
</pre>
<p>This shows the usage patterns being nearly identical in complexity for both
designs. The only actual added complexity occurs because of the use of operator
new in (4), (5) and (6) and the use of std::auto_ptr and boost::shared_ptr in
(4) and (6) respectively. However, that&#39;s not really much added complexity,
and C++ programmers are used to using these idioms any way. Some may dislike
the presence of operator new in user code, but this can be eliminated by proper
design of higher level concepts, such as the boost::thread_group class that
simplifies example (4) down to:</p>
<pre>
void foo()
{
thread_group threads;
for (int i=0; i&lt;NUM_THREADS; ++i)
threads.create_thread(&amp;bar);
threads.join_all();
}
</pre>
<p>So ease of use is really a wash and not much help in picking a design.</p>
<p>So what about performance? If you look at the above code examples we can analyze
the theoretical impact to performance that both designs have. For (1) we can
see that platforms that don&#39;t have a ref-counted native thread type (POSIX,
for instance) will be impacted by a thread_ref design. Even if the native thread
type is ref-counted there may be an impact if more state information has to
be maintained for concepts foreign to the native API, such as clean up stacks
for Win32 implementations. For (2) the performance impact will be identical
to (1). The same for (3). For (4) things get a little more interesting and we
find that theoretically at least the thread_ref may perform faster since the
thread design requires dynamic memory allocation/deallocation. However, in practice
there may be dynamic allocation for the thread_ref design as well, it will just
be hidden from the user. As long as the implementation has to do dynamic allocations
the thread_ref loses again because of the reference management. For (5) we see
the same impact as we do for (4). For (6) we still have a possible impact to
the thread design because of dynamic allocation but thread_ref no longer suffers
because of its reference management, and in fact, theoretically at least, the
thread_ref may do a better job of managing the references. All of this indicates
that thread wins for (1), (2) and (3), with (4) and (5) the winner depends on
the implementation and the platform but the thread design probably has a better
chance, and with (6) it will again depend on the implementation and platform
but this time we favor thread_ref slightly. Given all of this it&#39;s a narrow
margin, but the thread design prevails.</p>
<p>Given this analysis, and the fact that noncopyable objects for system resources
are the normal designs that C++ programmers are used to dealing with, the <b>Boost.Threads</b>
library has gone with a noncopyable design.</p>
<h2><a name="events"></a>Rationale for not providing <i>Event Variables</i></h2>
<p><i>Event variables</i> are simply far too error-prone. <a href=
"condition.html">Condition variables</a> are a much safer alternative.</p>
<p>[Note that Graphical User Interface <i>events</i> are a different concept,
and are not what is being discussed here.]</p>
<p>Event variables were one of the first synchronization primitives. They are
still used today, for example, in the native Windows multithreading API.</p>
<p>Yet both respected computer science researchers and experienced multithreading
practitioners believe event variables are so inherently error-prone that they
should never be used, and thus should not be part of a multithreading library.</p>
<p>Per Brinch Hansen <a href="bibliography.html#Brinch-Hansen-73"> [Brinch Hansen
73]</a> analyzed event variables in some detail, pointing out [emphasis his]
that &quot;<i>event operations force the programmer to be aware of the relative
speeds of the sending and receiving processes</i>&quot;. His summary:</p>
<blockquote>
<p>We must therefore conclude that event variables of the previous type are
impractical for system design. <i>The effect of an interaction between two
processes must be independent of the speed at which it is carried out.</i></p>
</blockquote>
<p>Experienced programmers using the Windows platform today report that event
variables are a continuing source of errors, even after previous bad experiences
caused them to be very careful in their use of event variables. Overt problems
can be avoided, for example, by teaming the event variable with a mutex, but
that may just convert a <a href=
"definitions.html#Race condition">race condition</a> into another problem,
such as excessive resource use. One of the most distressing aspects of the experience
reports is the claim that many defects are latent. That is, the programs appear
to work correctly, but contain hidden timing dependencies which will cause them
to fail when environmental factors or usage patterns change, altering relative
thread timings.</p>
<p>The decision to exclude event variables from <b>Boost.Threads</b> has been
surprising to some Windows programmers. They have written programs which work
using event variables, and wonder what the problem is. It seems similar to the
&quot;goto considered harmful&quot; controversy of 30 years ago. It isn&#39;t
that events, like gotos, can&#39;t be made to work, but rather that virtually
all programs using alternatives will be easier to write, debug, read, maintain,
and be less likely to contain latent defects.</p>
<p>[Rationale provided by Beman Dawes]</p>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

244
doc/recursive_mutex.html Normal file
View File

@@ -0,0 +1,244 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Header &lt;boost/thread/recursive_mutex.hpp&gt;</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Header &lt;<a href="../../../boost/thread/recursive_mutex.hpp">boost/thread/recursive_mutex.hpp</a>&gt;</h2> </td>
</tr>
</table>
<hr>
<h2>Contents</h2>
<dl class="page-index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#classes">Classes</a></dt>
<dl class="page-index">
<dt><a href="#class-recursive_mutex">Class <code>recursive_mutex</code></a></dt>
<dl class="page-index">
<dt><a href="#class-recursive_mutex-synopsis">Class <code>recursive_mutex</code>
synopsis</a></dt>
<dt><a href="#class-recursive_mutex-ctors">Class <code>recursive_mutex</code>
constructors and destructor</a></dt>
</dl>
<dt><a href="#class-recursive_try_mutex">Class <code>recursive_try_mutex</code></a></dt>
<dl class="page-index">
<dt><a href="#class-recursive_try_mutex-synopsis">Class <code>recursive_try_mutex</code>
synopsis</a></dt>
<dt><a href="#class-recursive_try_mutex-ctors">Class <code>recursive_try_mutex</code>
constructors and destructor</a></dt>
</dl>
<dt><a href="#class-recursive_timed_mutex">Class <code>recursive_timed_mutex</code></a></dt>
<dl class="page-index">
<dt><a href="#class-recursive_timed_mutex-synopsis">Class <code>recursive_timed_mutex</code>
synopsis</a></dt>
<dt><a href="#class-recursive_timed_mutex-ctors">Class <code>recursive_timed_mutex</code>
constructors and destructor</a></dt>
</dl>
</dl>
<dt><a href="#examples">Example(s)</a></dt>
</dl>
<hr>
<h2><a name="introduction"></a>Introduction</h2>
<p>Include the header &lt;<a href="../../../boost/thread/recursive_mutex.hpp">boost/thread/recursive_mutex.hpp</a>&gt;
to define the <a href="#class-recursive_mutex">recursive_mutex</a>, <a href="#class-recursive_try_mutex">recursive_try_mutex</a>
and <a href="#class-recursive_timed_mutex">recursive_timed_mutex</a> classes.</p>
<p>The <a href="#class-recursive_mutex">recursive_mutex</a>, <a href="#class-recursive_try_mutex">recursive_try_mutex</a>
and <a href="#class-recursive_timed_mutex">recursive_timed_mutex</a> classes
are models of <a href="mutex_concept.html#Mutex-concept">Mutex</a>, <a href="mutex_concept.html#TryMutex-concept">TryMutex</a>,
and <a href="mutex_concept.html#TimedMutex-concept">TimedMutex</a> respectively.
These types should be used to synchronize access to shared resources when recursive
locking by a single thread is likely to occur. A good example for this is when
a class supplies &quot;internal synchronization&quot; to ensure <a href="definitions.html#Thread-safe">
thread-safety</a> and a function of the class may have to call other functions
of the class which also attempt to lock the mutex. For recursive locking mechanics,
see <a href="mutex.html">mutexes</a>.</p>
<p>Each class supplies one or more typedefs for lock types which model matching
lock concepts. For the best possible performance you should use the mutex class
that supports the minimum set of lock types that you need.</p>
<table summary="lock types" border="1" cellpadding="5">
<tr>
<td><b>Mutex Class</b></td>
<td><b>Lock name</b></td>
<td><b>Lock Concept</b></td>
</tr>
<tr>
<td valign="top"><a href="#recursive_mutex Synopsis"><code> recursive_mutex</code></a></td>
<td valign="middle"><code>scoped_lock</code></td>
<td valign="middle"><a href="lock_concept.html#ScopedLock"> ScopedLock</a></td>
</tr>
<tr>
<td valign="top"><code><a href="#recursive_try_mutex Synopsis"> recursive_try_mutex</a></code></td>
<td valign="middle"><code>scoped_lock<br>
scoped_try_lock</code></td>
<td valign="middle"><a href="lock_concept.html#ScopedLock"> ScopedLock</a><br>
<a href="lock_concept.html#ScopedTryLock"> ScopedTryLock</a></td>
</tr>
<tr>
<td valign="top"><code><a href=
"#recursive_timed_mutex Synopsis"> recursive_timed_mutex</a></code>
</td>
<td valign="middle"><code>scoped_lock<br>
scoped_try_lock<br>
scoped_timed_lock</code></td>
<td valign="middle"><a href="lock_concept.html#ScopedLock"> ScopedLock</a><br>
<a href="lock_concept.html#ScopedTryLock"> ScopedTryLock</a><br>
<a href="lock_concept.html#ScopedTimedLock"> ScopedTimedLock</a></td>
</tr>
</table>
<p>The <code>recursive_mutex</code>, <code>recursive_try_mutex</code> and <code>recursive_timed_mutex</code>
employ a <code>Recursive</code> <a href="mutex_concept.html#LockingStrategies">locking
strategy</a>, so attempts to recursively lock them succeed and an internal &quot;lock
count&quot; is maintained. Attempts to unlock them by a thread that does not
own a lock on them will result in <b>undefined behavior</b>.</p>
<p>The <code>recursive_mutex</code>, <code>recursive_try_mutex</code> and <code>recursive_timed_mutex</code>
leave the <a href=
"mutex_concept.html#SchedulingPolicies">scheduling policy</a> as <code>
Unspecified</code>. Programmers should assume that threads waiting for a lock
on objects of these types acquire the lock in a random order, even though the
specific behavior for a given platform may be different.</p>
<h2><a name="classes"></a>Classes</h2>
<h3><a name="class-recursive_mutex"></a>Class <code>recursive_mutex</code></h3>
<p>The <code>recursive_mutex</code> class is a model of <a href="mutex_concept.html#Mutex-concept">Mutex</a>
and <a href="overview.html#non-copyable">NonCopyable</a>, and provides no additional
facilities beyond the requirements of these concepts.</p>
<h4><a name="class-recursive_mutex-synopsis"></a>Class <code>recursive_mutex</code>
synopsis</h4>
<pre>
namespace boost
{
class recursive_mutex : private boost::noncopyable // Exposition only.
// Class recursive_mutex meets the NonCopyable requirement.
{
public:
typedef [implementation defined; see Introduction] scoped_lock;
recursive_mutex();
~recursive_mutex();
};
};
</pre>
<h4><a name="class-recursive_mutex-ctors"></a>Class <code>recursive_mutex</code>
constructors and destructor</h4>
<pre>
recursive_mutex();
</pre>
<dl class="function-semantics">
<dt><b>Postconditions:</b> <code>*this</code> is in an unlocked state.</dt>
</dl>
<pre>
~recursive_mutex();
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> <code>*this</code> is in an unlocked sate.</dt>
<dt><b>Danger:</b> Destruction of a locked mutex is a serious programming error
resulting in undefined behavior such as a program crash.</dt>
</dl>
<h3><a name="class-recursive_try_mutex"></a>Class <code>recursive_try_mutex</code></h3>
<p>The <code>recursive_try_mutex</code> class is a model of <a href="mutex_concept.html#TryMutex-concept">TryMutex</a>
and <a href="overview.html#non-copyable">NonCopyable</a>, and provides no additional
facilities beyond the requirements of these concepts.</p>
<h4><a name="class-recursive_try_mutex-synopsis"></a>Class <code>recursive_try_mutex</code>
synopsis</h4>
<pre>
namespace boost
{
class recursive_mutex : private boost::noncopyable // Exposition only.
// Class recursive_mutex meets the NonCopyable requirement.
{
Public:
typedef [implementation defined; see Introduction] scoped_lock;
typedef [implementation defined; see Introduction] scoped_try_lock;
recursive_try_mutex();
~recursive_try_mutex();
};
};
</pre>
<h4><a name="class-recursive_try_mutex-ctors"></a>Class <code>recursive_try_mutex</code>
constructors and destructor</h4>
<pre>
recursive_try_mutex();
</pre>
<dl class="function-semantics">
<dt><b>Postconditions:</b> <code>*this</code> is in an unlocked state.</dt>
</dl>
<pre>
~recursive_try_mutex();
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> <code>*this</code> is in an unlocked sate.</dt>
<dt><b>Danger:</b> Destruction of a locked mutex is a serious programming error
resulting in undefined behavior such as a program crash.</dt>
</dl>
<h3><a name="class-recursive_timed_mutex"></a>Class <code>recursive_timed_mutex</code></h3>
<p>The <code>recursive_timed_mutex</code> class is a model of <a href="mutex_concept.html#TimedMutex-concept">TimedMutex</a>
and <a href="overview.html#non-copyable">NonCopyable</a>, and provides no additional
facilities beyond the requirements of these concepts.</p>
<h4><a name="class-recursive_timed_mutex-synopsis"></a>Class <code>recursive_timed_mutex</code>
synopsis</h4>
<pre>
namespace boost
{
class recursive_timed_mutex : private boost::noncopyable // Exposition only.
// Class recursive_mutex meets the NonCopyable requirement.
{
Public:
typedef [implementation defined; see Introduction] scoped_lock;
typedef [implementation defined; see Introduction] scoped_try_lock;
typedef [implementation defined; see Introduction] scoped_timed_lock;
recursive_timed_mutex();
~recursive_timed_mutex();
};
};
</pre>
<h4><a name="class-recursive_timed_mutex-ctors"></a>Class <code>recursive_timed_mutex</code>
constructors and destructor</h4>
<pre>
recursive_timed_mutex();
</pre>
<dl class="function-semantics">
<dt><b>Postconditions:</b> <code>*this</code> is in an unlocked state.</dt>
</dl>
<pre>
~recursive_timed_mutex();
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> <code>*this</code> is in an unlocked sate.</dt>
<dt><b>Danger:</b> Destruction of a locked mutex is a serious programming error
resulting in undefined behavior such as a program crash.</dt>
</dl>
<h2><a name="examples"></a>Example(s)</h2>
<p><a href="../example/recursive_mutex.cpp">libs/thread/example/recursive_mutex.cpp</a></p>
<p>The output is:</p>
<pre>
count == 1
count == 2
count == 3
count == 4
</pre>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

247
doc/rw_lock_concept.html Normal file
View File

@@ -0,0 +1,247 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - RWLock Concepts</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">RWLock Concepts</h2>
</td>
</tr>
</table>
<hr>
<dl class="index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#requirements">Concept Requirements</a></dt>
<dl class="index">
<dt><a href="#lock-state-enumeration">Lock State Enumeration</a></dt>
<dt><a href="#RWLock-concept">RWLock Concept</a></dt>
<dt><a href="#ScopedRWLock-concept">ScopedRWLock Concept</a></dt>
<dt><a href="#ScopedTryRWLock-concept">ScopedTryRWLock Concept</a></dt>
<dt><a href="#ScopedTimedRWLock-concept">ScopedTimedRWLock Concept</a></dt>
</dl>
<dt><a href="#models">Models</a></h2>
<dt><a href="#footnotes">Footnotes</a></dt>
</dl>
<h2><a name="introduction"></a>Introduction</h2>
<p>The lock concepts provide exception safe means for locking and unlocking a
<a href="rw_mutex_concept.html"> rw_mutex model</a>. In other words they are
an implementation of the <i>Scoped Locking</i> <a href="bibliography.html#Schmidt 00">[Schmidt
00]</a> pattern. The <a href="#ScopedRWLock">ScopedRWLock</a> concept, with
<a href="#ScopedTryRWLock"> ScopedTryRWLock</a> and <a href="#ScopedTimedRWLock">ScopedTimedRWLock</a>
refinements, formalize the requirements.</p>
<p>Lock models are constructed with a reference to a <a href="mutex_concept.html">mutex
model</a> and typically acquire ownership of the <a href="mutex_concept.html">mutex
model</a> by setting its state to locked. They also ensure ownership is relinquished
in the destructor. Lock models also expose functions to query the lock status
and to manually lock and unlock the <a href="mutex_concept.html">mutex model</a>.</p>
<p>Instances of lock models are meant to be short lived, expected to be used at
block scope only. The lock models are not <a href="definitions.html#Thread-safe">thread-safe</a>.
Lock models must maintain state to indicate whether or not they've been locked
and this state is not protected by any synchronization concepts. For this reason
an instance of a lock model should never be shared between multiple threads.</p>
<h2><a name="requirements"></a>Concept Requirements</h2>
<p>[For documentation purposes, portions of the concept requirements are repeated
in the documentation for specific lock classes. Those copies need to be kept
in sync with the requirements here.]</p>
<h3><a name="lock-state-enumeration"></a>Lock State Enumeration</h3>
<p>An enumerated value that can be one of three possible values - {NO_LOCK, SHARED_LOCK,
or EXCL_LOCK).&nbsp; Each class modeling the Lock Concept will maintain this
state as its view of the lock-state of the controlled rw_mutex.</p>
<h3><a name="RWLock-concept"></a>RWLock Concept</h3>
<p>For a <a href="#ScopedRWLock">ScopedRWLock</a>, <a href="#ScopedTryRWLock">ScopedTryRWLock</a>,
or <a href="#ScopedTimedRWLock">ScopedTimedRWLock</a> type <code>L</code> and
an object <code>lk</code> and const object <code>clk</code> of that type, the
following expressions must be well-formed and have the indicated effects.</p>
<p>The Lock concept is used as a base for the <a href="#ScopedRWLock">ScopedRWLock</a>,
<a href="#ScopedTryRWLock">ScopedTryRWLock</a>, and <a href="#ScopedTimedRWLock">ScopedTimedRWLock</a>
refinements. The associated rw_mutex type is as specified for each of those
refinements respectively.</p>
<table summary="Lock expressions" border="1" cellpadding="5">
<tr>
<td><b>Expression</b></td>
<td><b>Effects</b></td>
</tr>
<tr>
<td valign="top"><code>(&amp;lk)-&gt;~L();</code></td>
<td><code>if (locked()) unlock();</code></td>
</tr>
<tr>
<td valign="top"><code>(&amp;clk)-&gt;operator const void*()</code></td>
<td>Returns type void*, non-zero if if the associated rw_mutex has been locked
by <code> clk</code>, otherwise 0.</td>
</tr>
<tr>
<td valign="top"><code>clk.locked()</code></td>
<td>Returns a <code>bool</code>, <code>(&amp;clk)-&gt;operator const void*()
!= 0</code></td>
</tr>
<tr>
<td valign="top"><code>clk.lockstate()</code></td>
<td><code>Returns an enumeration of the lock state,&nbsp;NO_LOCK, EXCL_LOCK
or SHARED_LOCK</code></td>
</tr>
<tr>
<td valign="top"><code>lk.wrlock()</code></td>
<td>Throws lock_error if locked(). If the associated rw_mutex is already locked
by some other thread, places the current thread in the <a href="definitions.html#State">
Blocked</a> state until the associated rw_mutex is unlocked, after which
the current thread is placed in the <a href="definitions.html#State">Ready</a>
state, eventually to be returned to the <a href="definitions.html#State">Running</a>
state.<br>
Postcondition: locked() and lockstate() == EXCL_LOCK</td>
</tr>
<tr>
<td valign="top"><code>lk.rdlock()</code></td>
<td>Throws lock_error if locked().&nbsp; If the associated rw_mutex cannot
immediately grant the shared lock, places the current thread in the <a href="definitions.html#State">
Blocked</a> state until the associated rw_ mutex can grant a shared lock,
after which the current thread is placed in the <a href="definitions.html#State">Ready</a>
state, eventually to be returned to the <a href="definitions.html#State">Running</a>
state.&nbsp;<br>
Postcondition: locked() and lockstate() == SHARED_LOCK</td>
</tr>
<tr>
<td valign="top"><code>lk.unlock()</code></td>
<td>If !locked(), throws lock_error, otherwise unlocks the associated rw_mutex.<br>
Postcondition: !locked()</td>
</tr>
</table>
<h3><a name="ScopedRWLock-concept"></a>ScopedRWLock Concept</h3>
<p>A ScopedRWLock must meet the <a href="#Lock">RWLock</a> requirements. For a
ScopedRWLock type <code>L</code> and an object <code>lk</code> of that type,
and an object <code>m</code> of a type meeting the <a href="mutex_concept.html#Mutex">
RWMutex</a> requirements, and an object <code>s</code> of type <code>lock_state</code>,
the following expressions must be well-formed and have the indicated effects.</p>
<table summary="ScopedRWLock expressions" border="1" cellpadding="5" width="732">
<tr>
<td width="91"><b>Expression</b></td>
<td width="609"><b>Effects</b></td>
</tr>
<tr>
<td valign="top" width="91"><code>L lk(m);</code></td>
<td width="609">Constructs an object <code>lk</code>, and associates rw_mutex
<code>m</code> with it, then calls <code>lock()</code></td>
</tr>
<tr>
<td valign="top" width="91"><code>L lk(m,s);</code></td>
<td width="609">Constructs an object <code>lk</code>, and associates rw_mutex
<code>m</code> with it, then if <code>s==SHARED_LOCK</code>, calls <code>sharedlock()
or if s==EXCL_LOCK then calls lock()</code></td>
</tr>
</table>
<h3><a name="ScopedTryRWLock-concept"></a>ScopedTryRWLock Concept</h3>
<p>A ScopedTryRWLock must meet the <a href="#Lock">RWLock</a> requirements. For
a ScopedTryRWLock type <code>L</code> and an object <code>lk</code> of that
type, and an object <code>m</code> of a type meeting the <a href="mutex_concept.html#TryMutex">
TryRWMutex</a> requirements, and an object <code>s</code> of type <code>lock_state</code>,
the following expressions must be well-formed and have the indicated effects.</p>
<table summary="ScopedTryRWLock expressions" border="1" cellpadding="5">
<tr>
<td width="157"><b>Expression</b></td>
<td><b>Effects</b></td>
</tr>
<tr>
<td valign="top" width="157"><code>L lk(m);</code></td>
<td>Constructs an object <code>lk</code>, and associates rw_mutex <code>m</code>
with it, then calls <code>try_lock()</code></td>
</tr>
<tr>
<td valign="top" width="157"><code>L lk(m,s);</code></td>
<td>Constructs an object <code>lk</code>, and associates rw_mutex <code>m</code>
with it, then if <code>s==SHARED_LOCK</code>, calls <code>sharedlock() or
if s==EXCL_LOCK then calls lock()</code></td>
</tr>
<tr>
<td valign="top" width="157"><code>lk.try_wrlock()</code></td>
<td>If locked(), throws <code>lock_error</code>. Makes a non-blocking attempt
to exclusive-lock the associated rw_mutex, returning <code>true</code> if
the lock attempt is successful, otherwise <code>false</code>.</td>
</tr>
<tr>
<td valign="top" width="157"><code>lk.try_rdlock()</code></td>
<td>If locked(), throws <code>lock_error</code>. Makes a non-blocking attempt
to shared-lock the associated rw_mutex, returning <code>true</code> if the
lock attempt is successful, otherwise <code>false</code>.</td>
</tr>
</table>
<h3><a name="ScopedTimedRWLock-concept"></a>ScopedTimedRWLock Concept</h3>
<p>A ScopedTimedRWLock must meet the <a href="#Lock">RWLock</a> requirements.
For a ScopedTimedRWLock type <code>L</code> and an object <code>lk</code> of
that type, and an object <code>m</code> of a type meeting the <a href="mutex_concept.html#TimedMutex">
TimedRWMutex</a> requirements, and an object <code>s</code> of type <code>lock_state</code>,
and an object <code>t</code> of type <code><a href="xtime.html">xtime</a></code>,
the following expressions must be well-formed and have the indicated effects.</p>
<table summary="ScopedTimedRWLock expressions" border="1" cellpadding="5">
<tr>
<td width="164"><b>Expression</b></td>
<td><b>Effects</b></td>
</tr>
<tr>
<td valign="top" width="164"><code>L lk(m,t);</code></td>
<td>Constructs an object <code>lk</code>, and associates rw_mutex <code>m</code>
with it, then calls <code>timed_lock(t)</code></td>
</tr>
<tr>
<td valign="top" width="164"><code>L lk(m,s);</code></td>
<td>Constructs an object <code>lk</code>, and associates rw_ mutex <code>m</code>
with it, then if <code>s==SHARED_LOCK</code>, calls <code>sharedlock() or
if s==EXCL_LOCK then calls lock()</code></td>
</tr>
<tr>
<td valign="top" width="164"><code>lk.timed_wrlock(t)</code></td>
<td>If locked(), throws lock_error. Makes a blocking attempt to exclusive-lock
the associated rw_mutex, and returns <code>true</code> if successful within
the specified time <code>t</code>, otherwise <code>false</code>.</td>
</tr>
<tr>
<td valign="top" width="164"><code>lk.timed_rdlock(t)</code></td>
<td>If locked(), throws lock_error. Makes a blocking attempt to shared-lock
the associated rw_mutex, and returns <code>true</code> if successful within
the specified time <code>t</code>, otherwise <code>false</code>.</td>
</tr>
</table>
<h2><a name="models"></a>Models</h2>
<p><b>Boost.Threads</b> currently supplies three classes which model lock concepts.</p>
<p>These classes are normally accessed via typedefs of the same name supplied
by a <a href="mutex_concept.html"> mutex model</a>.</p>
<table summary="Lock concept classes" border="1" cellpadding="5">
<tr>
<td><b>Concept</b></td>
<td><b>Refines</b></td>
<td><b>Classes Modeling the Concept</b></td>
</tr>
<tr>
<td><a href="#ScopedRWLock">ScopedRWLock</a></td>
<td>&nbsp;</td>
<td><a href="scoped_rw_lock.html">scoped_rw_lock</a></td>
</tr>
<tr>
<td><a href="#ScopedTryRWLock">ScopedTryRWLock</a></td>
<td><a href="#ScopedRWLock">ScopedRWLock</a></td>
<td><a href="scoped_try_rw_lock.html">scoped_try_rw_lock</a> </td>
</tr>
<tr>
<td><a href="#ScopedTimedRWLock">ScopedTimedRWLock</a></td>
<td><a href="#ScopedRWLock">ScopedRWLock</a></td>
<td><a href="scoped_timed_rw_lock.html">scoped_timed_rw_lock</a></td>
</tr>
</table>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:{{address}}">{{author}}</a> 2002. All Rights
Reserved.</i></p>
</body>
</html>

353
doc/rw_mutex.html Normal file
View File

@@ -0,0 +1,353 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Header &lt;boost/thread/rw_mutex.hpp&gt;</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Header &lt;<a href="../../../boost/thread/rw_mutex.hpp">boost/thread/rw_mutex.hpp</a>&gt;</h2>
</td>
</tr>
</table>
<hr>
<h2>Contents</h2>
<dl class="page-index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#macros">Macros</a></dt>
<dl class="page-index">
<dt><a href="#macro-spec">{{macro name}}</a></dt>
</dl>
<dt><a href="#values">Values</a></dt>
<dl class="page-index">
<dt><a href="#value-spec">{{value name}}</a></dt>
</dl>
<dt><a href="#types">Types</a></dt>
<dl class="page-index">
<dt><a href="#type-spec">{{type name}}</a></dt>
</dl>
<dt><a href="#classes">Classes</a></dt>
<dl class="page-index">
<dt><a href="#class-spec">Class <code>{{class name}}</code></a></dt>
<dl class="page-index">
<dt><a href="#class-spec-synopsis">Class <code>{{class name}}</code> synopsis</a></dt>
<dt><a href="#class-spec-ctors">Class <code>{{class name}}</code> constructors
and destructor</a></dt>
<dt><a href="#class-spec-comparisons">Class <code>{{class name}}</code>
comparison functions</a></dt>
<dt><a href="#class-spec-modifiers">Class <code>{{class name}}</code> modifier
functions</a></dt>
<dt><a href="#class-spec-observers">Class <code>{{class name}}</code> observer
functions</a></dt>
<dt><a href="#class-spec-statics">Class <code>{{class name}}</code> static
functions</a></dt>
</dl>
</dl>
<dt><a href="#functions">Functions</a></dt>
<dl class="page-index">
<dt><a href="#function-spec">{{function name}}</a></dt>
</dl>
<dt><a href="#objects">Objects</a></dt>
<dl class="page-index">
<dt><a href="#object-spec">{{object name}}</a></dt>
</dl>
<dt><a href="#examples">Example(s)</a></dt>
</dl>
<hr>
<h2><a name="introduction"></a>Introduction</h2>
<p>The <tt><a href="#rw_mutex Synopsis">rw_mutex</a></tt>, <tt><a href="#try_rw_mutex Synopsis">
try_rw_mutex</a></tt> and <tt><a href="#timed_rw_mutex Synopsis">timed_rw_mutex</a></tt>
classes define full featured models of the <a href="rw_mutex_concept.html#rw_mutex">
RWMutex</a>, <a href="rw_mutex_concept.html#TryMutex">TryRWMutex</a>, and <a href="rw_mutex_concept.html#TimedMutex">
TimedRWMutex</a> concepts. These types should be used to synchronize access
to shared resources.&nbsp; Recursive or non-recursive locking mechanics are
acheived by supplying the appropriate Mutex type as a parameter.</p>
<p>Each class supplies one or more typedefs for lock types which model matching
lock concepts. For the best possible performance you should use the rw_mutex
class that supports the minimum set of lock types that you need.</p>
<table summary="lock types" border="1" cellpadding="5">
<tr>
<td><b>rw_mutex Class</b></td>
<td><b>Lock name</b></td>
<td><b>Implementation defined Lock Type</b></td>
<td><b>Lock Concept</b></td>
</tr>
<tr>
<td valign="top"><a href="#rw_mutex Synopsis"><code> rw_mutex</code></a></td>
<td valign="center"><code> scoped_rw_lock</code></td>
<td valign="center"><code><a href="scoped_lock.html">boost::</a></code><a href="scoped_lock.html"><code>detail::thread::scoped_rw_lock&lt;rw_mutex&gt;</code></a></td>
<td valign="center">ScopedRWLock</td>
</tr>
<tr>
<td valign="top"><tt><a href="#try_rw_mutex Synopsis"> try_rw_mutex</a></tt>
</td>
<td valign="center"><code> scoped_rw_lock<br>
scoped_try_rw_lock</code></td>
<td valign="center"><code><a href="scoped_lock.html">boost::</a></code><a href="scoped_lock.html"><code>detail::thread::scoped_rw_lock&lt;try_rw_mutex&gt;</code></a>
<code><a href="scoped_try_lock.html"> <br>
</a><a href="scoped_lock.html">boost::</a></code><a href="scoped_lock.html"><code>detail::thread::scoped_try_rw_lock&lt;try_rw_mutex&gt;</code></a></td>
<td valign="center">ScopedRWLock<br>
ScopedRWTryLock</td>
</tr>
<tr>
<td valign="top"><code><a href="#timed_rw_mutex Synopsis"> timed_rw_mutex</a></code>
</td>
<td valign="center"><code> scoped_rw_lock<br>
scoped_try_rw_lock<br>
scoped_timed_rw_lock</code></td>
<td valign="center"><code><a href="scoped_lock.html">boost::</a></code><a href="scoped_lock.html"><code>detail::thread::scoped_rw_lock&lt;timed_rw_mutex&gt;</code></a>
<code><a href="scoped_try_lock.html"> <br>
</a><a href="scoped_lock.html">boost::</a></code><a href="scoped_lock.html"><code>detail::thread::scoped_try_rw_lock&lt;timed_rw_mutex&gt;</code></a><a href="scoped_timed_lock.html"><code><br>
</code></a><code><a href="scoped_lock.html">boost::</a></code><a href="scoped_lock.html"><code>detail::thread::scoped_timed_rw_lock&lt;timed_rw_mutex&gt;</code></a></td>
<td valign="center">ScopedRWLock<br>
ScopedRWTryLock<br>
ScopedRWTimedLock</td>
</tr>
</table>
<p>The <tt>rw_mutex</tt>, <tt>try_rw_mutex</tt> and <tt>timed_rw_mutex</tt> classes
leave the locking strategy as Unspecified.&nbsp; Programmers should assume that
threads that lock a rw_mutex, try_rw_mutex, or timed_rw_mutex multiple times
will deadlock, unless all of the lock requests are for read-locks.&nbsp;&nbsp;</p>
<p>The <tt>rw_mutex</tt>, <tt>try_rw_mutex</tt> and <tt>timed_rw_mutex</tt> allow
the programmer to explicitly choose&nbsp;the <a href="rw_mutex_concept.html#SchedulingPolicies">
scheduling policy</a> for the lock.&nbsp; This scheduling policy will dictate
how competing readers and writers will acquire the lock.&nbsp; It does not,
however, dictate the order that individual read or write requests will be granted,
in comparison to other requests of the same type.&nbsp;&nbsp;Programmers should
assume that threads waiting for a lock on objects of these types acquire the
lock in a random order, even though the specific behavior for a given platform
may be different.</p>
<H2>Release Notes/Caveats</H2>
<UL>
<LI> Self-deadlock is virtually guaranteed if a thread tries to lock the same
rw_mutex multiple times, unless all locks are read-locks (but see below)</LI>
<LI> This implementation does not protect against reader overflow.&nbsp; If
more than INT_MAX readers obtain or try to obtain a lock simultaneously, the
behavior is undefined.&nbsp; This will be addressed in a future release, but
it seems that detecting this condition &amp; reporting an error or throwing
an exception should suffice for realistic uses.&nbsp; Having readers beyond
INT_MAX wait for the count to decrease only pushes the overflow problem onto
another variable...&nbsp; Suggestions?</LI>
<LI> See the comments at the head of rw_mutex.cpp for a description of the implementation
itself.</LI>
</UL>
<h2><a name="macros"></a>Macros</h2>
<p><a name="macro-spec"></a>{{Macro specifications}}</p>
<h2><a name="values"></a>Values</h2>
<pre>
namespace boost {
typedef enum
{
sp_writer_priority,
sp_reader_priority,
sp_alternating_many_reads,
sp_alternating_single_reads
} rw_scheduling_policy;
typedef enum
{
NO_LOCK,
SHARED_LOCK,
EXCL_LOCK
} lockstate;
}
</pre>
<h2><a name="types"></a>Types</h2>
<p><a name="type-spec"></a>{{Type specifications}}</p>
<h2><a name="classes"></a>Classes</h2>
<h3><a name="class-rw_mutex"></a>Class <code>rw_mutex</code></h3>
<p>{{text}}</p>
<h4><a name="class-rw_mutex-synopsis"></a>Class <code>rw_mutex</code> synopsis</h4>
<pre>
namespace boost
{
class rw_mutex : private <a href="../../utility/utility.htm">boost::noncopyable</a> // Exposition only.
// Class mutex meets the <a href="overview.html#non-copyable">NonCopyable</a> requirement.
{
public:
typedef <i>[implementation defined; see <a href="#introduction">Introduction</a>]</i> scoped_rw_lock;
rw_mutex(rw_scheduling_policy sp=sp_writer_priority);
~rw_mutex();
};
};
</pre>
<h4><a name="class-rw_mutex-ctors"></a>Class <code>rw_mutex</code> constructors
and destructor</h4>
<pre>
rw_mutex(rw_scheduling_policy sp=sp_writer_priority);
</pre>
<dl class="function-semantics">
<dt><b>Postconditions:</b> <code>*this</code> is in the NO_LOCK state.</dt>
</dl>
<pre>
~rw_mutex();
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> <code>*this</code> is in the NO_LOCK state.</dt>
<dt><b>Effects:</b> Destroys <code>*this</code>.</dt>
<dt><b>Danger:</b> Destruction of a locked rw_mutex is a serious programming
error resulting in undefined behavior such as a program crash.</dt>
</dl>
<h3><a name="class-rw_try_mutex"></a>Class <code>rw_try_mutex</code></h3>
<p>{{text}}</p>
<h4><a name="class-rw_try_mutex-synopsis"></a>Class <code>rw_try_mutex</code>
synopsis</h4>
<pre>
namespace boost
{
class rw_mutex : private <a href="../../utility/utility.htm">boost::noncopyable</a> // Exposition only.
// Class mutex meets the <a href="overview.html#non-copyable">NonCopyable</a> requirement.
{
public:
typedef <i>[implementation defined; see <a href="#introduction">Introduction</a>]</i> scoped_rw_lock;
typedef <i>[implementation defined; see <a href="#introduction">Introduction</a>]</i> scoped_rw_try_lock;
rw_try_mutex(rw_scheduling_policy sp=sp_writer_priority);
~rw_try_mutex();
};
};
</pre>
<h4><a name="class-rw_try_mutex-ctors"></a>Class <code>rw_try_mutex</code> constructors
and destructor</h4>
<pre>
rw_try_mutex(rw_scheduling_policy sp=sp_writer_priority);
</pre>
<dl class="function-semantics">
<dt><b>Postconditions:</b> <code>*this</code> is in the NO_LOCK state.</dt>
</dl>
<pre>
~rw_try_mutex();
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> <code>*this</code> is in the NO_LOCK state.</dt>
<dt><b>Effects:</b> Destroys <code>*this</code>.</dt>
<dt><b>Danger:</b> Destruction of a locked rw_mutex is a serious programming
error resulting in undefined behavior such as a program crash.</dt>
</dl>
<h3><a name="class-rw_timed_mutex"></a>Class <code>rw_timed_mutex</code></h3>
<p>{{text}}</p>
<h4><a name="class-rw_timed_mutex-synopsis"></a>Class <code>rw_timed_mutex</code>
synopsis</h4>
<pre>
namespace boost
{
class rw_timed_mutex : private <a href="../../utility/utility.htm">boost::noncopyable</a> // Exposition only.
// Class mutex meets the <a href="overview.html#non-copyable">NonCopyable</a> requirement.
{
public:
typedef <i>[implementation defined; see <a href="#introduction">Introduction</a>]</i> scoped_rw_lock;
typedef <i>[implementation defined; see <a href="#introduction">Introduction</a>]</i> scoped_rw_try_lock;
typedef <i>[implementation defined; see <a href="#introduction">Introduction</a>]</i> scoped_rw_timed_lock;
rw_timed_mutex(rw_scheduling_policy sp=sp_writer_priority);
~rw_timed_mutex();
};
};
</pre>
<h4><a name="class-rw_timed_mutex-ctors"></a>Class <code>rw_timed_mutex</code>
constructors and destructor</h4>
<pre>
rw_timed_mutex(rw_scheduling_policy sp=sp_writer_priority);
</pre>
<dl class="function-semantics">
<dt><b>Postconditions:</b> <code>*this</code> is in the NO_LOCK state.</dt>
</dl>
<pre>
~rw_timed_mutex();
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> <code>*this</code> is in the NO_LOCK state.</dt>
<dt><b>Effects:</b> Destroys <code>*this</code>.</dt>
<dt><b>Danger:</b> Destruction of a locked rw_mutex is a serious programming
error resulting in undefined behavior such as a program crash.</dt>
</dl>
<h2><a name="examples"></a>Example(s)</h2>
<pre>
#include <a href="../../../boost/thread/rw_mutex.hpp">&lt;boost/thread/rw_mutex.hpp&gt;</a>
#include &lt;boost/thread/mutex.hpp&gt;
#include <a href="../../../boost/thread/thread.hpp">&lt;boost/thread/thread.hpp&gt;</a>
#include &lt;iostream&gt;
boost::mutex io_mutex; // The iostreams are not guaranteed to be <a href="definitions.html#Thread-safe">thread-safe</a>!
class counter
{
public:
counter() : count(0) { }
int increment() {
boost::rw_mutex::scoped_lock scoped_rw_lock(rw_mutex);
return ++count;
}
int get() {
boost::rw_mutex::scoped_lock scoped_rw_lock(rw_mutex,SHARED_LOCK);
return count;
}
private:
boost::rw_mutex rwm(boost::sp_writer_priority);
int count;
};
counter c;
void change_count(void*)
{
int i = c.increment();
boost::rw_mutex::scoped_lock scoped_lock(io_mutex);
std::cout &lt;&lt; "count == " &lt;&lt; i &lt;&lt; std::endl;
}
void get_count(void*)
{
int i = c.get();
boost::rw_mutex::scoped_lock scoped_lock(io_mutex);
std::cout &lt;&lt; "get_count == " &lt;&lt; i &lt;&lt; std::endl;
}
int main(int, char*[])
{
const int num_threads = 4;
boost::thread_group thrds;
for (int i=0; i &lt; num_threads; ++i)
{
thrds.create_thread(&amp;change_count, 0);
thrds.create_thread(&amp;get_count,0);
}
thrds.join_all();
return 0;
}
</pre>
<p>Typicial output might be:</p>
<pre>
count == 1
get_count == 1
get_count == 1
count == 2
count == 3
get_count == 3
count == 4
get_count == 4
</pre>
<p>Of course, exact output is platform dependent since the locking behavior with
competing readers and writers is undefined.</p>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:{{address}}">{{author}}</a> 2002. All Rights
Reserved.</i></p>
</body>
</html>

611
doc/rw_mutex_concept.html Normal file
View File

@@ -0,0 +1,611 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - RWMutex Concept</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">RWMutex Concept</h2>
</td>
</tr>
</table>
<hr>
<dl class="index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#locking-strategies">Locking Strategies</a></dt>
<dl class="page-index">
<dt><a href="#locking-strategy-recursive">Recursive</a></dt>
<dt><a href="#locking-strategy-checked">Checked</a></dt>
<dt><a href="#locking-strategy-unchecked">Unchecked</a></dt>
<dt><a href="#locking-strategy-unspecified">Unspecified</a></dt>
</dl>
<dt><a href="#scheduling-policies">Scheduling Policies</a></dt>
<dt><a href="#requirements">Concept Requirements</a></dt>
<dt><a href="#models">Models</a></dt>
</dl>
<h2><a name="introduction"></a>Introduction</h2>
<p>A rw_mutex (short for reader-writer mutual-exclusion) concept serializes access
to a resource shared between multiple threads, where multiple readers can share
simultaneous access, but writers require exclusive access.&nbsp; The <a href="#Mutex">
RWMutex</a> concept, with <a href="#TryMutex">TryRWMutex</a> and <a href="#TimedMutex">
TimedRWMutex</a> refinements, formalize the requirements. A model that implements
RWMutex and its refinements has three states: <b>shared-locked</b> ,<b>exclusive-locked</b>
and <b>unlocked</b>. Before reading from a&nbsp; shared resource, a thread <b>shared-locks</b>
a Boost.Threads rw_mutex model object, insuring <a href="definitions.html#Thread-safe">
thread-safe</a> access for reading from the shared resource. Before writing
to a shared resource, a thread <b>exclusive-locks</b> a Boost.Threads rw_mutex
model object, insuring <a href="definitions.html#Thread-safe">thread-safe</a>
access for altering the shared resource.&nbsp; When use of the shared resource
is complete, the thread unlocks the mutex model object, allowing another thread
to acquire the lock and use the shared resource.</p>
<p> Some traditional C thread APIs like Pthreads provide implementations for rw_mutex
(also known as reader-writer locks).&nbsp; Others like Windows thread APIs do
not provide a rw_mutex primitive.&nbsp; Some of those APIs expose functions
to lock and unlock a rw_mutex model. This is dangerous since it's easy to forget
to unlock a locked rw_mutex. When the flow of control is complex, with multiple
return points, the likelihood of forgetting to unlock a rw_mutex model would
become even greater. When exceptions are thrown, it becomes nearly impossible
to ensure that the rw_mutex is unlocked properly when using these traditional
API's. The result is <a href="definitions.html#Deadlock">deadlock</a>.</p>
<p>Many C++ threading libraries use a pattern known as <i>Scoped Locking</i> <a href="bibliography.html#Schmidt 00">
[Schmidt 00]</a> to free the programmer from the need to explicitly lock and
unlock rw_mutexes. With this pattern, a <a href="lock_concept.html">lock concept</a>
is employed where the lock model's constructor locks the associated rw_mutex
model and the destructor automatically does the unlocking. The <b>Boost.Threads</b>
library takes this pattern to the extreme in that lock concepts are the only
way to lock and unlock a rw_mutex model: lock and unlock functions are not exposed
by any <b>Boost.Threads</b> rw_mutex models. This helps to ensure safe usage
patterns, especially when code throws exceptions.</p>
<h2><a name="locking-strategies"></a>Locking Strategies</h2>
<P>Every rw_mutex model follows one of several locking strategies. These strategies
define the semantics for the locking operation when the calling thread already
owns a lock on the rw_mutex model.</P>
<h3><a name="locking-strategy-recursive"></a>Recursive</h3>
<P>With a recursive locking strategy when a thread attempts to acquire an additional&nbsp;lock
on the rw_mutex model for which it already owns a lock, the operation is successful,
except&nbsp;possibly in the case where a shared-lock holding thread attempts
to&nbsp;obtain an exclusive lock.&nbsp; </P>
<P>
<TABLE id="Table9" width="100%" border="1">
<TR>
<TD width="22%">Lock Type Held</TD>
<TD width="18%">Lock Request Type</TD>
<TD width="60%">Action</TD>
</TR>
<TR>
<TD width="22%">shared-lock</TD>
<TD width="18%">shared-lock</TD>
<TD width="60%">Grant the shared lock immediately</TD>
</TR>
<TR>
<TD width="22%">shared-lock</TD>
<TD width="18%">exclusive-lock</TD>
<TD width="60%">
<P>If this thread is the only holder of the shared-lock, grants the exclusive
lock immediately.&nbsp; Otherwise throws lock_error() exception.</P>
</TD>
</TR>
<TR>
<TD width="22%">exclusive-locked</TD>
<TD width="18%">shared-lock</TD>
<TD width="60%">Grants the (additional) shared lock immediately.</TD>
</TR>
<TR>
<TD width="22%">exclusive-locked</TD>
<TD width="18%">exclusive-lock</TD>
<TD width="60%"> Grant the exclusive lock immediately</TD>
</TR>
</TABLE>
<P>Internally a lock count is maintained and the owning thread must unlock the
mutex model the same number of times that it's locked it before the mutex model's
state returns to unlocked. Since mutex models in <B>Boost.Threads</B> expose
locking functionality only through lock concepts, a thread will always unlock
a mutex model the same number of times that it locked it. This helps to eliminate
a whole set of errors typically found in traditional C style thread APIs.</P>
<P>Classes <A href="recursive_mutex.html">recursive_rw_mutex</A>, <A href="recursive_mutex.html">
recursive_try_rw_mutex</A> and <A href="recursive_mutex.html">recursive_timed_rw_mutex</A>
will use this locking strategy.&nbsp; Successful implementation of this locking
strategy may require thread identification (see below).</P>
<h3><a name="locking-strategy-checked"></a>Checked</h3>
<P>With a checked locking strategy when a thread attempts to acquire a lock on
the mutex model for which the thread already owns a lock, the operation will
fail with some sort of error indication, except in the case of multiple&nbsp;shared-lock
acquisition which is&nbsp;a normal operation for ANY RWMutex. &nbsp;Further,
attempts by a thread to unlock a mutex that was not locked by the thread will
also return some sort of error indication. In <B>Boost.Threads</B>, an exception
of type <A href="lock_error.html">lock_error</A> would be thrown in these cases.</P>
<B>
<P>
<TABLE id="Table10" width="100%" border="1">
<TR>
<TD width="22%">Lock Type Held</TD>
<TD width="18%">Lock Request Type</TD>
<TD width="60%">Action</TD>
</TR>
<TR>
<TD width="22%">shared-lock</TD>
<TD width="18%">shared-lock</TD>
<TD width="60%">Grant the shared lock immediately</TD>
</TR>
<TR>
<TD width="22%">shared-lock</TD>
<TD width="18%">exclusive-lock</TD>
<TD width="60%">
<P>Throw lock_error()</P>
</TD>
</TR>
<TR>
<TD width="22%">exclusive-locked</TD>
<TD width="18%">shared-lock</TD>
<TD width="60%">Throw lock_error()</TD>
</TR>
<TR>
<TD width="22%">exclusive-locked</TD>
<TD width="18%">exclusive-lock</TD>
<TD width="60%"> Throw lock_error()</TD>
</TR>
</TABLE>
<p></P>
</B>
<P><B> Boost.Threads</b> does not currently provide any rw_mutex models that use
this strategy.&nbsp; A successful implementation of this locking strategy would
likely require thread identification.</P>
<h3><a name="locking-strategy-unchecked"></a>Unchecked</h3>
<P>With an unchecked locking strategy when a thread attempts to acquire a lock
on the rw_mutex model for which the thread already owns a lock the operation
will <A href="definitions.html#Deadlock"> deadlock</A>. In general this locking
strategy is less safe than a checked or recursive strategy, but it can be&nbsp;a
faster strategy and so is employed by many libraries.</P>
<P>
<TABLE id="Table11" width="100%" border="1">
<TR>
<TD width="22%">Lock Type Held</TD>
<TD width="18%">Lock Request Type</TD>
<TD width="60%">Action</TD>
</TR>
<TR>
<TD width="22%">shared-lock</TD>
<TD width="18%">shared-lock</TD>
<TD width="60%">Grant the shared lock immediately</TD>
</TR>
<TR>
<TD width="22%">shared-lock</TD>
<TD width="18%">exclusive-lock</TD>
<TD width="60%">
<P>Deadlock</P>
</TD>
</TR>
<TR>
<TD width="22%">exclusive-locked</TD>
<TD width="18%">shared-lock</TD>
<TD width="60%">Deadlock</TD>
</TR>
<TR>
<TD width="22%">exclusive-locked</TD>
<TD width="18%">exclusive-lock</TD>
<TD width="60%"> Deadlock</TD>
</TR>
</TABLE>
<p></P>
<P><B>Boost.Threads</B> does not currently provide any mutex models that use this
strategy.&nbsp; For RWMutexes on platforms that contain natively recursive synchronization
primitives, implementing a guaranteed-deadlock can actually involve extra work,
and would likely require thread identification.</P>
<h3><a name="locking-strategy-unspecified"></a>Unspecified</h3>
<P>With an unspecified locking strategy, when a thread attempts to acquire a lock
on a rw_mutex model for which the thread already owns a lock the operation results
in <B>undefined behavior</B>. When a rw_mutex model has an unspecified locking
strategy the programmer must assume that the rw_mutex model instead uses an
unchecked strategy as the worse case, although some platforms may exhibit a
mix of unchecked and recursive behavior.</P>
<P>
<TABLE id="Table12" width="100%" border="1">
<TR>
<TD width="22%">Lock Type Held</TD>
<TD width="18%">Lock Request Type</TD>
<TD width="60%">Action</TD>
</TR>
<TR>
<TD width="22%">shared-lock</TD>
<TD width="18%">shared-lock</TD>
<TD width="60%">Grant the shared lock immediately</TD>
</TR>
<TR>
<TD width="22%">shared-lock</TD>
<TD width="18%">exclusive-lock</TD>
<TD width="60%">
<P>Undefined, but generally deadlock</P>
</TD>
</TR>
<TR>
<TD width="22%">exclusive-locked</TD>
<TD width="18%">shared-lock</TD>
<TD width="60%">Undefined, but generally deadlock</TD>
</TR>
<TR>
<TD width="22%">exclusive-locked</TD>
<TD width="18%">exclusive-lock</TD>
<TD width="60%"> Undefined, but generally deadlock</TD>
</TR>
</TABLE>
<p></P>
<P>In general a rw_mutex model with an unspecified locking strategy is unsafe,
and it requires programmer discipline to use the rw_mutex model properly. However,
this strategy allows an implementation to be as fast as possible with no restrictions
on its implementation. This is especially true for portable implementations
that wrap the native threading support of a platform. For this reason, the classes
<A href="rw_mutex.html">rw_mutex</A>, <A href="rw_mutex.html">try_rw_mutex</A>
and <A href="rw_mutex.html">timed_rw_mutex</A> use this locking strategy despite
the lack of safety.</P>
<h3>An Aside - Thread Identification</h3>
<P>RWMutexes can support specific Locking Strategies (recursive and checked) which
help to detect and protect against self-deadlock.&nbsp; Self-deadlock can occur
when a holder of a locked RWMutex attempts to obtain another lock.&nbsp; Given
an implemention "I" which is susceptible to self-deadlock but otherwise correct
and efficient, a recursive or checked implementation "Ir" or "Ic" can use the
same basic implementation, but make special checks against self-deadlock by
tracking the identities of thread(s) currently holding locks.&nbsp; This approach
makes deadlock detection othrogonal to the basic RWMutex implementaion.&nbsp;
</P>
<P> Alternatively, a different basic implementation for RWMutex concepts&nbsp;,
I' (I-Prime) may exist which uses recursive or checked versions of synchronization
primitives to produce a recursive or checked RWMutex while still providing flexibility
in terms of Scheduling Policies.
<P>Please refer to the <b>Boost.Threads</b> <a href="mutex_concept.html#LockingStrategies">
mutex concept</a> documentation for a discussion of locking strategies.&nbsp;
The rw_mutex supports both the <a href="mutex_concept.html#Recursive"> recursive</a>
and <a href="mutex_concept.html#Unspecified">unspecified</a> locking strategies.&nbsp;
RWMutexes are parameterized on a Mutex type which they use to control exclusive-locking
and access to internal state.
<H3>Another Aside - <A name="LockingPromotion">Lock Promotion</A></H3>
<P>RWMutexes can support lock promotion, where a mutex which is in the shared-locked
state transitions to an exclusive-locked state without releasing the lock.&nbsp;
If this functionality is supported at all by Boost.Threads, it will only be
through an explicit promote() operations.&nbsp; Extra care must be taken to
ensure that only one thread holding a shared lock can block awaiting promotion
at any given time.&nbsp;&nbsp;If more than one shared-lock holder is allowed
to enter a blocked state while waiting to be promoted, deadlock will result
since both threads will be waiting for the other to release their shared lock.
<h2><a name="scheduling-policies"></a>Scheduling Policies</h2>
<p>Every rw_mutex model follows one of several scheduling policies. These policies
define the semantics when the mutex model is unlocked and there is more than
one thread waiting to acquire a lock. In other words, the policy defines which
waiting thread shall acquire the lock.&nbsp; For rw_mutex, it is particularly
important to define the behavior when threads are requesting both shared and
exclusive access simultaneously.&nbsp; This will be referred to as "inter-class
scheduling".&nbsp;&nbsp;</p>
<p>For some types of inter-class scheduling, an intra-class scheduling policy
can also be defined that will describe the order in which waiting threads of
the same class will acquire the thread.</p>
<h3><a name="ReaderPriority">ReaderPriority</a></h3>
<p>With ReaderPriority, any pending request for a shared lock will have priority
over a pending request for an exclusive lock, irrespective of the current lock
state of the rw_mutex, and irrespective of the relative order that the pending
requests arrive.</p>
<table border="1" width="100%" id="Table1">
<tr>
<td width="22%">Current rw_mutex state</td>
<td width="18%">Request Type</td>
<td width="60%">Action</td>
</tr>
<tr>
<td width="22%">unlocked</td>
<td width="18%">shared-lock</td>
<td width="60%">Grant the shared lock immediately</td>
</tr>
<tr>
<td width="22%">shared-locked</td>
<td width="18%">shared-lock</td>
<td width="60%">Grant the additional shared lock immediately.</td>
</tr>
<tr>
<td width="22%">exclusive-locked</td>
<td width="18%">shared-lock</td>
<td width="60%">Wait to acquire the lock until the thread holding the exclusive-lock
releases its lock.&nbsp; A shared lock will be granted to all pending readers
before&nbsp;any other thread can acquire an exclusive lock.</td>
</tr>
<tr>
<td width="22%">unlocked</td>
<td width="18%">exclusive-lock</td>
<td width="60%">Grant the exclusive lock immediately, if and only if there
are no pending shared-lock requests.</td>
</tr>
<tr>
<td width="22%">shared-locked</td>
<td width="18%">exclusive-lock</td>
<td width="60%"> Wait to acquire the lock until all threads holding shared
locks release their locks -AND- no requests for shared locks exist.&nbsp;
If other exclusive-lock requests exist, the lock is granted in accordance
with the intra-request scheduling policy.</td>
</tr>
<tr>
<td width="22%">exclusive-locked</td>
<td width="18%">exclusive-lock</td>
<td width="60%">Wait to acquire the lock until the thread holding the exclusive
lock releases its lock -AND- no requests for shared locks exist.&nbsp; If
other exclusive-lock requests exist, the lock is granted in accordance with
the intra-request scheduling policy.</td>
</tr>
</table>
<h3><a name="WriterPriority">WriterPriority</a></h3>
<p>With WriterPriority, any pending request for an exclusive lock will have priority
over a pending request for a shared lock, irrespective of the current lock state
of the rw_mutex, and irrespective of the relative order that the pending requests
arrive.</p>
<table border="1" width="100%" id="Table2">
<tr>
<td width="22%">Current rw_mutex state</td>
<td width="18%">Request Type</td>
<td width="60%">Action</td>
</tr>
<tr>
<td width="22%">unlocked</td>
<td width="18%">shared-lock</td>
<td width="60%">Grant the shared lock immediately.</td>
</tr>
<tr>
<td width="22%">shared-locked</td>
<td width="18%">shared-lock</td>
<td width="60%">Grant the additional shared lock immediately, -IF- no outstanding
requests for an exclusive lock exist.</td>
</tr>
<tr>
<td width="22%">exclusive-locked</td>
<td width="18%">shared-lock</td>
<td width="60%"> Wait to acquire the lock until the thread holding the exclusive-lock
releases its lock.&nbsp; The shared lock will be granted once&nbsp;no other
outstanding exclusive-lock requests exist.</td>
</tr>
<tr>
<td width="22%">unlocked</td>
<td width="18%">exclusive-lock</td>
<td width="60%">Grant the exclusive lock immediately.</td>
</tr>
<tr>
<td width="22%">shared-locked</td>
<td width="18%">exclusive-lock</td>
<td width="60%">Wait to acquire the lock until all threads holding shared
locks release their locks.&nbsp; If other exclusive-lock requests exist,
the lock is granted in accordance with the intra-request scheduling policy.&nbsp;
This request will be granted before any new shared-lock requests are granted.</td>
</tr>
<tr>
<td width="22%">exclusive-locked</td>
<td width="18%">exclusive-lock</td>
<td width="60%">Wait to acquire the lock until the thread holding the exclusive
lock releases its lock.&nbsp; If other exclusive-lock requests exist, the
lock is granted in accordance with the intra-request scheduling policy.&nbsp;
This request will be granted before any new shared-lock requests are granted.</td>
</tr>
</table>
<h3><a name="AlteratingManyPriority">AlternatingPriority</a>/ManyReads</h3>
<p>With AlternatingPriority/ManyReads, reader or writer starvation is avoided
by alternatively granting shared or exclusive access when pending requests exist
for both types of locks.&nbsp; Outstanding shared-lock requests are treated
as a group when it is the "reader's turn"</p>
<table border="1" width="100%" id="Table3">
<tr>
<td width="22%">Current rw_mutex state</td>
<td width="18%">Request Type</td>
<td width="60%">Action</td>
</tr>
<tr>
<td width="22%">unlocked</td>
<td width="18%">shared-lock</td>
<td width="60%">Grant the shared lock immediately.</td>
</tr>
<tr>
<td width="22%">shared-locked</td>
<td width="18%">shared-lock</td>
<td width="60%">Grant the additional shared lock immediately, -IF- no outstanding
requests for an exclusive lock exist.&nbsp; If outstanding exclusive-lock
requests exist, this lock will not be granted until at least one of the
exclusive locks is granted and released. If other shared-lock requests exist,
all shared-locks will be granted as a group.</td>
</tr>
<tr>
<td width="22%">exclusive-locked</td>
<td width="18%">shared-lock</td>
<td width="60%"> Wait to acquire the lock until the thread holding the exclusive-lock
releases its lock.&nbsp; If other outstanding exclusive-lock requests exist,
they will have to wait until all current shared-lock requests are serviced.</td>
</tr>
<tr>
<td width="22%">unlocked</td>
<td width="18%">exclusive-lock</td>
<td width="60%">Grant the exclusive lock immediately.</td>
</tr>
<tr>
<td width="22%">shared-locked</td>
<td width="18%">exclusive-lock</td>
<td width="60%">
<P>Wait to acquire the lock until all threads holding shared locks release
their locks.&nbsp; </P>
<P>If other&nbsp;exclusive-lock requests exist, this lock will be granted
to one of them in accordance with the intra-request scheduling policy.</P>
</td>
</tr>
<tr>
<td width="22%">exclusive-locked</td>
<td width="18%">exclusive-lock</td>
<td width="60%">Wait to acquire the lock until the thread holding the exclusive
lock releases its lock.&nbsp;&nbsp; If other outstanding shared-lock requests
exist, this lock will not be granted until all of the currently waiting
shared locks&nbsp;are granted and released.&nbsp; If other exclusive-lock
requests exist, this lock will be granted in accordance with the intra-request
scheduling policy.</td>
</tr>
</table>
<H3>
<H3><A name="AlteratingSinglePriority">AlternatingPriority</A>/SingleReads</H3>
</H3>
<P>With AlternatingPriority/ManyReads, reader or writer starvation is avoided
by alternatively granting shared or exclusive access when pending requests exist
for both types of locks.&nbsp; Outstanding shared-lock requests are services
one at a time&nbsp;when it is the "reader's turn"</P>
<H3>
<TABLE id="Table13" width="100%" border="1">
<TR>
<TD width="22%">Current rw_mutex state</TD>
<TD width="18%">Request Type</TD>
<TD width="60%">Action</TD>
</TR>
<TR>
<TD width="22%">unlocked</TD>
<TD width="18%">shared-lock</TD>
<TD width="60%">Grant the shared lock immediately.</TD>
</TR>
<TR>
<TD width="22%">shared-locked</TD>
<TD width="18%">shared-lock</TD>
<TD width="60%">Grant the additional shared lock immediately, -IF- no outstanding
requests for an exclusive lock exist.&nbsp; If outstanding exclusive-lock
requests exist, this lock will not be granted until at least one of the
exclusive locks is granted and released. </TD>
</TR>
<TR>
<TD width="22%">exclusive-locked</TD>
<TD width="18%">shared-lock</TD>
<TD width="60%">
<P>Wait to acquire the lock until the thread holding the exclusive-lock
releases its lock.</P>
<P>If other outstanding exclusive-lock requests exist, exactly one shared-lock
request will be granted before the next exclusive lock is granted.</P>
</TD>
</TR>
<TR>
<TD width="22%">unlocked</TD>
<TD width="18%">exclusive-lock</TD>
<TD width="60%">Grant the exclusive lock immediately.</TD>
</TR>
<TR>
<TD width="22%">shared-locked</TD>
<TD width="18%">exclusive-lock</TD>
<TD width="60%">
<P>Wait to acquire the lock until all threads holding shared locks release
their locks.&nbsp; </P>
<P>If other&nbsp;exclusive-lock requests exist, this lock will be granted
to one of them in accordance with the intra-request scheduling policy.</P>
</TD>
</TR>
<TR>
<TD width="22%">exclusive-locked</TD>
<TD width="18%">exclusive-lock</TD>
<TD width="60%">Wait to acquire the lock until the thread holding the exclusive
lock releases its lock.&nbsp;&nbsp; If other outstanding shared-lock requests
exist, this lock can not be granted until exactly one shared-lock request
is granted and released.&nbsp; If other exclusive-lock requests exist,
this lock will be granted in accordance with the intra-request scheduling
policy.</TD>
</TR>
</TABLE>
</H3>
<h3>Intra-Request Scheduling Policy</h3>
<p>Please refer to the <b>Boost.Threads</b> <a href="mutex_concept.html#SchedulingPolicies">
mutex concept</a> documentation for a discussion of mutex scheduling policies,
which are identical to RWMutex Intra-Request scheduling policies.&nbsp; The
rw_mutex supports only the <a href="mutex_concept.html#UnspecifiedScheduling">
Unspecified</a> intra-request scheduling policy.&nbsp; That is, given a set
of threads waiting for exclusive locks, the order (amongst themselves) in which
they receive the lock is unspecified.</p>
<h2><a name="requirements"></a>Concept Requirements</h2>
<h3>RW<a name="Mutex">Mutex</a> Concept</h3>
<p>A RWMutex object has three states: shared-locked, exclusive-locked, and unlocked.
RWMutex object state can only be determined by an object meeting the <a href="rw_lock_concept.html#ScopedLock">
ScopedRWLock</a> requirements and constructed for the RWMutex object.</p>
<p>A RWMutex is <a href="../../utility/utility.htm#Class noncopyable">noncopyable</a>.</p>
<p> For a RWMutex type RWM,&nbsp;and an object m of that type, the following expressions
must be well-formed and have the indicated effects.</p>
<table summary="Mutex expressions" border="1" cellpadding="5" id="Table5">
<tr>
<td><b>Expression</b></td>
<td><b>Effects</b></td>
</tr>
<tr>
<td><code>RWM m;</code></td>
<td>Constructs a rw_mutex object m. Post-condition: m is unlocked.</td>
</tr>
<tr>
<td><code>(&amp;m)-&gt;~RWM();</code></td>
<td>Precondition: m is unlocked. Destroys a rw_mutex object m.</td>
</tr>
<tr>
<td><code>RWM::scoped_rw_lock</code></td>
<td>A type meeting the <a href="rw_lock_concept.html#ScopedRWLock">ScopedRWLock</a>
requirements.&nbsp;&nbsp;</td>
</tr>
</table>
<h3><a name="TryMutex">TryRWMutex</a> Concept</h3>
<p>A TryRWMutex must meet the <a href="#RWMutex">RWMutex</a> requirements. In
addition, for a TryRWMutex type RWM and an object m of that type, the following
expressions must be well-formed and have the indicated effects.</p>
<table summary="TryMutex expressions" border="1" cellpadding="5" id="Table6">
<tr>
<td><b>Expression</b></td>
<td><b>Effects</b></td>
</tr>
<tr>
<td><code>RWM::scoped_try_rw_lock</code></td>
<td>A type meeting the <a href="rw_lock_concept.html#ScopedTryRWLock">ScopedTryRWLock</a>
requirements.</td>
</tr>
</table>
<h3><a name="TimedMutex">TimedRWMutex</a> Concept</h3>
<p>A TimedRWMutex must meet the <a href="#TryMutex">TryRWMutex</a> requirements.
In addition, for a TimedRWMutex type RWM and an object m of that type, the following
expressions must be well-formed and have the indicated effects.</p>
<table summary="TimedMutex expressions" border="1" cellpadding="5" id="Table7">
<tr>
<td><b>Expression</b></td>
<td><b>Effects</b></td>
</tr>
<tr>
<td><code>RWM::scoped_timed_rw_lock</code></td>
<td>A type meeting the <a href="rw_lock_concept.html#ScopedTimedRWLock">ScopedTimedRWLock</a>
requirements.</td>
</tr>
</table>
<h2><a name="models"></a>Models</h2>
<p><b>Boost.Threads</b> currently supplies three classes which model rw_mutex
concepts.</p>
<table summary="Mutex concept classes" border="1" cellpadding="5" id="Table8">
<tr>
<td><b>Concept</b></td>
<td><b>Refines</b></td>
<td><b>Classes Modeling the Concept</b></td>
</tr>
<tr>
<td valign="top"><a href="#Mutex">RWMutex</a></td>
<td valign="top">&nbsp;</td>
<td><a href="rw_mutex.html">rw_mutex&lt;Mutex&gt;</a></td>
</tr>
<tr>
<td valign="top"><a href="#TryMutex">TryRWMutex</a></td>
<td valign="top"><a href="#Mutex">RWMutex</a></td>
<td><a href="rw_mutex.html">try_rw_mutex&lt;TryMutex&gt; </a> </td>
</tr>
<tr>
<td valign="top"><a href="#TimedMutex">TimedRWMutex</a></td>
<td valign="top"><a href="#TryMutex">TryRWMutex</a></td>
<td><a href="rw_mutex.html">timed_rw_mutex&lt;TimedMutex&gt; </a> </td>
</tr>
</table>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:{{address}}">{{author}}</a> 2002. All Rights
Reserved.</i></p>
</body>
</html>

View File

@@ -1,44 +0,0 @@
[/
(C) Copyright 2007-8 Anthony Williams.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
]
[section:shared_mutex Class `shared_mutex`]
#include <boost/thread/shared_mutex.hpp>
class shared_mutex
{
public:
shared_mutex();
~shared_mutex();
void lock_shared();
bool try_lock_shared();
bool timed_lock_shared(system_time const& timeout);
void unlock_shared();
void lock();
bool try_lock();
bool timed_lock(system_time const& timeout);
void unlock();
void lock_upgrade();
void unlock_upgrade();
void unlock_upgrade_and_lock();
void unlock_and_lock_upgrade();
void unlock_and_lock_shared();
void unlock_upgrade_and_lock_shared();
};
The class `boost::shared_mutex` provides an implementation of a multiple-reader / single-writer mutex. It implements the
__upgrade_lockable_concept__.
Multiple concurrent calls to __lock_ref__, __try_lock_ref__, __timed_lock_ref__, __lock_shared_ref__, __try_lock_shared_ref__ and
__timed_lock_shared_ref__ shall be permitted.
[endsect]

323
doc/thread.html Normal file
View File

@@ -0,0 +1,323 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - &lt;boost/thread.hpp&gt;</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Header &lt;<a href="../../../boost/thread/thread.hpp">boost/thread.hpp</a>&gt;</h2>
</td>
</tr>
</table>
<hr>
<h2>Contents</h2>
<dl class="page-index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#classes">Classes</a></dt>
<dl class="page-index">
<dt><a href="#class-thread">Class <code>thread</code></a></dt>
<dl class="page-index">
<dt><a href="#class-thread-synopsis">Class <code>thread</code> synopsis</a></dt>
<dt><a href="#class-thread-ctors">Class <code>thread</code> constructors
and destructor</a></dt>
<dt><a href="#class-thread-comparisons">Class <code>thread</code> comparison
functions</a></dt>
<dt><a href="#class-thread-modifiers">Class <code>thread</code> modifier
functions</a></dt>
<dt><a href="#class-thread-statics">Class <code>thread</code> static functions</a></dt>
</dl>
<dt><a href="#class-thread_group">Class <code>thread_group</code></a></dt>
<dl class="page-index">
<dt><a href="#class-thread_group-synopsis">Class <code>thread_group</code>
synopsis</a></dt>
<dt><a href="#class-thread_group-ctors">Class <code>thread_group</code>
constructors and destructor</a></dt>
<dt><a href="#class-thread_group-modifiers">Class <code>thread_group</code>
modifier functions</a></dt>
</dl>
</dl>
<dt><a href="#examples">Example(s)</a></dt>
<dl class="page-index">
<dt><a href="#example-thread">Simple usage of <code>boost::thread</code></a></dt>
<dt><a href="#example-thread_group">Simple usage of <code>boost::thread_group</code></a></dt>
</dl>
</dl>
<hr>
<h2><a name="introduction"></a>Introduction</h2>
<p>The header &lt;<a href="../../../boost/thread/thread.hpp">boost/thread.hpp</a>&gt;
defines the classes <a href="#class-thread">thread</a> and <a href="#class-thread_group">thread_group</a>
which are used to create, observe and manage threads and groups of threads.</p>
<h2><a name="classes"></a>Classes</h2>
<h3><a name="class-thread"></a>Class <code>thread</code></h3>
<p>The <code>thread</code> class represents threads of execution, and provides
the functionality to create and manage threads within the <b> Boost.Threads</b>
library. See <a href="definitions.html"> Definitions</a> for a precise description
of &quot;thread of execution&quot;, and for definitions of threading related
terms and of thread states such as &quot;blocked&quot;.</p>
<p>A thread of execution has an initial function. For the program&#39;s initial
thread, the initial function is <code>main()</code>. For other threads, the
initial function is <code>operator()</code> of the function object passed to
the class <code>thread</code> constructor.</p>
<p>A thread of execution is said to be &quot;finished&quot; or &quot;finished
execution&quot; when its initial function returns or is terminated. This includes
completion of all thread cleanup handlers, and completion of the normal C++
function return behaviors, such as destruction of automatic storage (stack)
objects and releasing any associated implementation resources.</p>
<p>A thread object has an associated state which is either &quot;joinable&quot;
or &quot;non-joinable&quot;.</p>
<p>Except as described below, the policy used by an implementation of <b>Boost.Threads</b>
to schedule transitions between thread states is unspecified.</p>
<p><b>Note:</b> Just as the lifetime of a file may be different from the lifetime
of an iostream object which represents the file, the lifetime of a thread of
execution may be different from the <code> thread</code> object which represents
the thread of execution. In particular, after a call to <code>join()</code>,
the thread of execution will no longer exist even though the <code>thread</code>
object continues to exist until the end of its normal lifetime. The converse
is also possible; if a <code>thread</code> object is destroyed without <code>join()</code>
having first been called, the thread of execution continues until its initial
function completes.</p>
<h4><a name="class-thread-synopsis"></a>Class <code>thread</code> synopsis</h4>
<pre>
namespace boost {
class thread : <a href=
"../../utility/utility.htm#Class noncopyable">boost::noncopyable</a> // Exposition only.
// Class thread meets the <a href=
"overview.html#non-copyable">NonCopyable</a> requirement.
{
public:
thread();
explicit thread(const boost::function0&lt;void&gt;&amp; threadfunc);
~thread();
bool operator==(const thread&amp; rhs) const;
bool operator!=(const thread&amp; rhs) const;
void join();
static void sleep(const xtime&amp; xt);
static void yield();
};
} // namespace boost
</pre>
<h4><a name="class-thread-ctors"></a>Class <code>thread</code> constructors and
destructor</h4>
<pre>
thread();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Constructs a <code>thread</code> object representing the
current thread of execution.</dt>
<dt><b>Postconditions:</b> <code>*this</code> is non-joinable.</dt>
<dt><b>Danger:</b> <code>*this</code> is valid only within the current thread.</dt>
</dl>
<pre>
thread(const <a href="../../function/index.html">boost::function0</a>&lt;void&gt;&amp; threadfunc);
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Starts a new thread of execution and constructs a <code>thread</code>
object representing it. Copies <code> threadfunc</code> (which in turn copies
the function object wrapped by <code>threadfunc</code>) to an internal location
which persists for the lifetime of the new thread of execution. Calls <code>operator()</code>
on the copy of the <code>threadfunc</code> function object in the new thread
of execution.</dt>
<dt><b>Postconditions:</b> <code>*this</code> is joinable.</dt>
<dt><b>Throws:</b> <code>boost::thread_resource_error</code> if a new thread
of execution cannot be started.</dt>
</dl>
<pre>
~Thread();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Destroys <code>*this</code>. The actual thread of execution
may continue to execute after the <code>thread</code> object has been destroyed.</dt>
<dt><b>Note:</b> If <code>*this</code> is joinable the actual thread of execution
becomes &quot;detached&quot;. Any resources used by the thread will be reclaimed
when the thread of execution completes. To ensure such a thread of execution
runs to completion before the <code> thread</code> object is destroyed, call
<code>join()</code>.</dt>
</dl>
<h4><a name="class-thread-comparisons"></a>Class <code>thread</code> comparison
functions</h4>
<pre>
bool operator==(const thread&amp; rhs) const;
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> The thread is non-terminated or <code>*this</code> is joinable.</dt>
<dt><b>Returns:</b> <code>true</code> if <code>*this</code> and <code> rhs</code>
represent the same thread of execution.</dt>
</dl>
<pre>
bool operator!=(const thread&amp; rhs) const;
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> The thread is non-terminated or <code>*this</code> is joinable.</dt>
<dt><b>Returns:</b> <code>!(*this==rhs)</code>.</dt>
</dl>
<h4><a name="class-thread-modifiers"></a>Class <code>thread</code> modifier functions</h4>
<pre>
void join();
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> <code>*this</code> is joinable.</dt>
<dt><b>Effects:</b> The current thread of execution blocks until the initial
function of the thread of execution represented by <code> *this</code> finishes
and all resources are reclaimed.</dt>
<dt><b>Postconditions:</b> <code>*this</code> is non-joinable.</dt>
<dt><b>Notes:</b> If <code>*this == thread()</code> the result is implementation
defined. If the implementation doesn&#39;t detect this the result will be
<a href="definitions.html#Deadlock"> deadlock</a>.</dt>
</dl>
<h4><a name="class-thread-statics"></a>Class <code>thread</code> static functions</h4>
<pre>
static void sleep(const <a href="xtime.html">xtime</a>&amp; XT);
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> The current thread of execution blocks until <code> XT</code>
is reached.</dt>
</dl>
<pre>
static void yield();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> The current thread of execution is placed in the &quot;ready&quot;
state.</dt>
<dt><b>Notes:</b> Allow the current thread to give up the rest of its time slice
(or other scheduling quota) to another thread. Particularly useful in non-preemptive
implementations.</dt>
</dl>
<h3><a name="class-thread_group"></a>Class <code>thread_group</code></h3>
<p>The <tt>thread_group</tt> class provides a container for easy grouping of threads
to simplify several common thread creation and management idioms.</p>
<p>All <tt>thread_group</tt> member functions are <a href=
"definitions.html#thread-safe">thread-safe</a>, except destruction.</p>
<h4><a name="class-thread_group-synopsis"></a>Class <code>thread_group</code>
synopsis</h4>
<pre>
namespace boost {
class thread_group : <a href=
"../../utility/utility.htm#Class noncopyable">boost::noncopyable</a>
{
public:
thread_group();
~thread_group();
thread* create_thread(const boost::function0&lt;void&gt;&amp; threadfunc);
void add_thread(thread* thrd);
void remove_thread(thread* thrd);
void join_all();
};
} // namespace boost
</pre>
<h4><a name="class-thread_group-ctors"></a>Class <code>thread_group</code> constructors
and destructor</h4>
<pre>
thread_group();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Constructs an empty <code>thread_group</code> container.</dt>
</dl>
<pre>
~thread_group();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Destroys each contained thread object. Destroys <code>*this</code>.</dt>
<dt><b>Notes:</b> Behavior is undefined if another thread references *this during
the execution of the destructor.</dt>
</dl>
<h4><a name="class-thread_group-modifiers"></a>Class <code>thread_group</code>
modifier functions</h4>
<pre>
thread* create_thread(const boost::function0&lt;void&gt;&amp; threadfunc);
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Creates a new <tt>thread</tt> object that executes <tt>threadfunc</tt>
and adds it to the <tt>thread_group</tt> container object&#39;s list of managed
<tt>thread</tt> objects.</dt>
<dt><b>Returns:</b> Pointer to the newly created thread.</dt>
</dl>
<pre>
void add_thread(thread* thrd);
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Adds <tt>thrd</tt> to the <tt>thread_group</tt> object&#39;s
list of managed <tt>thread</tt> objects. The <tt>thrd</tt> object must have
been allocated via operator new and will be deleted when the group is destroyed.</dt>
</dl>
<pre>
Void remove_thread(thread* thrd);
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Removes <code>*this</code>&#39;s list of managed <tt>thread</tt>
objects.</dt>
<dt><b>Throws:</b> ? if <tt>thrd</tt> is not it <code>*this</code>&#39;s list
of managed <tt>thread</tt> objects.</dt>
</dl>
<pre>
Void join_all();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Calls <code>join()</code> on each of the managed <tt>thread</tt>
objects.</dt>
</dl>
<h2><a name="functions"></a>Functions</h2>
<pre>
<a name="function-spec"></a>{{function}}
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> {{text}}</dt>
<dt><b>Effects:</b> {{text}}</dt>
<dt><b>Postconditions:</b> {{text}}</dt>
<dt><b>Returns:</b> {{text}}</dt>
<dt><b>Throws:</b> {{text}}</dt>
<dt><b>Complexity:</b> {{text}}</dt>
<dt><b>Rationale:</b> {{text}}</dt>
</dl>
<h2><a name="objects"></a>Objects</h2>
<p><a name="object-spec"></a>{{Object specifications}}</p>
<h2><a name="examples"></a>Example(s)</h2>
<h3><a name="example-thread"></a>Simple usage of <code>boost::thread</code></h3>
<p><a href="../example/thread.cpp">libs/thread/example/thread.cpp</a></p>
<p>The output is:</p>
<pre>
setting alarm for 5 seconds...
alarm sounded...
</pre>
<h3><a name="example-thread_group"></a>Simple usage of <code>boost::thread_group</code></h3>
<p><a href="../example/thread_group.cpp">libs/thread/example/thread_group.cpp</a></p>
<p>The output is:</p>
<pre>
count = 1
count = 2
count = 3
count = 4
count = 5
count = 6
count = 7
count = 8
count = 9
count = 10
</pre>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

View File

@@ -1,168 +0,0 @@
[/
(C) Copyright 2007-8 Anthony Williams.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
]
[article Thread
[quickbook 1.4]
[authors [Williams, Anthony]]
[copyright 2007-8 Anthony Williams]
[purpose C++ Library for launching threads and synchronizing data between them]
[category text]
[license
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
[@http://www.boost.org/LICENSE_1_0.txt])
]
]
[template lockable_concept_link[link_text] [link thread.synchronization.mutex_concepts.lockable [link_text]]]
[def __lockable_concept__ [lockable_concept_link `Lockable` concept]]
[def __lockable_concept_type__ [lockable_concept_link `Lockable`]]
[template timed_lockable_concept_link[link_text] [link thread.synchronization.mutex_concepts.timed_lockable [link_text]]]
[def __timed_lockable_concept__ [timed_lockable_concept_link `TimedLockable` concept]]
[def __timed_lockable_concept_type__ [timed_lockable_concept_link `TimedLockable`]]
[template shared_lockable_concept_link[link_text] [link thread.synchronization.mutex_concepts.shared_lockable [link_text]]]
[def __shared_lockable_concept__ [shared_lockable_concept_link `SharedLockable` concept]]
[def __shared_lockable_concept_type__ [shared_lockable_concept_link `SharedLockable`]]
[template upgrade_lockable_concept_link[link_text] [link thread.synchronization.mutex_concepts.upgrade_lockable [link_text]]]
[def __upgrade_lockable_concept__ [upgrade_lockable_concept_link `UpgradeLockable` concept]]
[def __upgrade_lockable_concept_type__ [upgrade_lockable_concept_link `UpgradeLockable`]]
[template lock_ref_link[link_text] [link thread.synchronization.mutex_concepts.lockable.lock [link_text]]]
[def __lock_ref__ [lock_ref_link `lock()`]]
[template lock_multiple_ref_link[link_text] [link thread.synchronization.lock_functions.lock_multiple [link_text]]]
[def __lock_multiple_ref__ [lock_multiple_ref_link `lock()`]]
[template try_lock_multiple_ref_link[link_text] [link thread.synchronization.lock_functions.try_lock_multiple [link_text]]]
[def __try_lock_multiple_ref__ [try_lock_multiple_ref_link `try_lock()`]]
[template unlock_ref_link[link_text] [link thread.synchronization.mutex_concepts.lockable.unlock [link_text]]]
[def __unlock_ref__ [unlock_ref_link `unlock()`]]
[template try_lock_ref_link[link_text] [link thread.synchronization.mutex_concepts.lockable.try_lock [link_text]]]
[def __try_lock_ref__ [try_lock_ref_link `try_lock()`]]
[template timed_lock_ref_link[link_text] [link thread.synchronization.mutex_concepts.timed_lockable.timed_lock [link_text]]]
[def __timed_lock_ref__ [timed_lock_ref_link `timed_lock()`]]
[template timed_lock_duration_ref_link[link_text] [link thread.synchronization.mutex_concepts.timed_lockable.timed_lock_duration [link_text]]]
[def __timed_lock_duration_ref__ [timed_lock_duration_ref_link `timed_lock()`]]
[template lock_shared_ref_link[link_text] [link thread.synchronization.mutex_concepts.shared_lockable.lock_shared [link_text]]]
[def __lock_shared_ref__ [lock_shared_ref_link `lock_shared()`]]
[template unlock_shared_ref_link[link_text] [link thread.synchronization.mutex_concepts.shared_lockable.unlock_shared [link_text]]]
[def __unlock_shared_ref__ [unlock_shared_ref_link `unlock_shared()`]]
[template try_lock_shared_ref_link[link_text] [link thread.synchronization.mutex_concepts.shared_lockable.try_lock_shared [link_text]]]
[def __try_lock_shared_ref__ [try_lock_shared_ref_link `try_lock_shared()`]]
[template timed_lock_shared_ref_link[link_text] [link thread.synchronization.mutex_concepts.shared_lockable.timed_lock_shared [link_text]]]
[def __timed_lock_shared_ref__ [timed_lock_shared_ref_link `timed_lock_shared()`]]
[template timed_lock_shared_duration_ref_link[link_text] [link thread.synchronization.mutex_concepts.shared_lockable.timed_lock_shared_duration [link_text]]]
[def __timed_lock_shared_duration_ref__ [timed_lock_shared_duration_ref_link `timed_lock_shared()`]]
[template lock_upgrade_ref_link[link_text] [link thread.synchronization.mutex_concepts.upgrade_lockable.lock_upgrade [link_text]]]
[def __lock_upgrade_ref__ [lock_upgrade_ref_link `lock_upgrade()`]]
[template unlock_upgrade_ref_link[link_text] [link thread.synchronization.mutex_concepts.upgrade_lockable.unlock_upgrade [link_text]]]
[def __unlock_upgrade_ref__ [unlock_upgrade_ref_link `unlock_upgrade()`]]
[template unlock_upgrade_and_lock_ref_link[link_text] [link thread.synchronization.mutex_concepts.upgrade_lockable.unlock_upgrade_and_lock [link_text]]]
[def __unlock_upgrade_and_lock_ref__ [unlock_upgrade_and_lock_ref_link `unlock_upgrade_and_lock()`]]
[template unlock_and_lock_upgrade_ref_link[link_text] [link thread.synchronization.mutex_concepts.upgrade_lockable.unlock_and_lock_upgrade [link_text]]]
[def __unlock_and_lock_upgrade_ref__ [unlock_and_lock_upgrade_ref_link `unlock_and_lock_upgrade()`]]
[template unlock_upgrade_and_lock_shared_ref_link[link_text] [link thread.synchronization.mutex_concepts.upgrade_lockable.unlock_upgrade_and_lock_shared [link_text]]]
[def __unlock_upgrade_and_lock_shared_ref__ [unlock_upgrade_and_lock_shared_ref_link `unlock_upgrade_and_lock_shared()`]]
[template owns_lock_ref_link[link_text] [link thread.synchronization.locks.unique_lock.owns_lock [link_text]]]
[def __owns_lock_ref__ [owns_lock_ref_link `owns_lock()`]]
[template owns_lock_shared_ref_link[link_text] [link thread.synchronization.locks.shared_lock.owns_lock [link_text]]]
[def __owns_lock_shared_ref__ [owns_lock_shared_ref_link `owns_lock()`]]
[template mutex_func_ref_link[link_text] [link thread.synchronization.locks.unique_lock.mutex [link_text]]]
[def __mutex_func_ref__ [mutex_func_ref_link `mutex()`]]
[def __boost_thread__ [*Boost.Thread]]
[def __not_a_thread__ ['Not-a-Thread]]
[def __interruption_points__ [link interruption_points ['interruption points]]]
[def __mutex__ [link thread.synchronization.mutex_types.mutex `boost::mutex`]]
[def __try_mutex__ [link thread.synchronization.mutex_types.try_mutex `boost::try_mutex`]]
[def __timed_mutex__ [link thread.synchronization.mutex_types.timed_mutex `boost::timed_mutex`]]
[def __recursive_mutex__ [link thread.synchronization.mutex_types.recursive_mutex `boost::recursive_mutex`]]
[def __recursive_try_mutex__ [link thread.synchronization.mutex_types.recursive_try_mutex `boost::recursive_try_mutex`]]
[def __recursive_timed_mutex__ [link thread.synchronization.mutex_types.recursive_timed_mutex `boost::recursive_timed_mutex`]]
[def __shared_mutex__ [link thread.synchronization.mutex_types.shared_mutex `boost::shared_mutex`]]
[template unique_lock_link[link_text] [link thread.synchronization.locks.unique_lock [link_text]]]
[def __lock_guard__ [link thread.synchronization.locks.lock_guard `boost::lock_guard`]]
[def __unique_lock__ [unique_lock_link `boost::unique_lock`]]
[def __shared_lock__ [link thread.synchronization.locks.shared_lock `boost::shared_lock`]]
[def __upgrade_lock__ [link thread.synchronization.locks.upgrade_lock `boost::upgrade_lock`]]
[def __upgrade_to_unique_lock__ [link thread.synchronization.locks.upgrade_to_unique_lock `boost::upgrade_to_unique_lock`]]
[def __thread__ [link thread.thread_management.thread `boost::thread`]]
[def __thread_id__ [link thread.thread_management.thread.id `boost::thread::id`]]
[template join_link[link_text] [link thread.thread_management.thread.join [link_text]]]
[def __join__ [join_link `join()`]]
[template timed_join_link[link_text] [link thread.thread_management.thread.timed_join [link_text]]]
[def __timed_join__ [timed_join_link `timed_join()`]]
[def __detach__ [link thread.thread_management.thread.detach `detach()`]]
[def __interrupt__ [link thread.thread_management.thread.interrupt `interrupt()`]]
[def __sleep__ [link thread.thread_management.this_thread.sleep `boost::this_thread::sleep()`]]
[def __interruption_enabled__ [link thread.thread_management.this_thread.interruption_enabled `boost::this_thread::interruption_enabled()`]]
[def __interruption_requested__ [link thread.thread_management.this_thread.interruption_requested `boost::this_thread::interruption_requested()`]]
[def __interruption_point__ [link thread.thread_management.this_thread.interruption_point `boost::this_thread::interruption_point()`]]
[def __disable_interruption__ [link thread.thread_management.this_thread.disable_interruption `boost::this_thread::disable_interruption`]]
[def __restore_interruption__ [link thread.thread_management.this_thread.restore_interruption `boost::this_thread::restore_interruption`]]
[def __thread_resource_error__ `boost::thread_resource_error`]
[def __thread_interrupted__ `boost::thread_interrupted`]
[def __barrier__ [link thread.synchronization.barriers.barrier `boost::barrier`]]
[template cond_wait_link[link_text] [link thread.synchronization.condvar_ref.condition_variable.wait [link_text]]]
[def __cond_wait__ [cond_wait_link `wait()`]]
[template cond_timed_wait_link[link_text] [link thread.synchronization.condvar_ref.condition_variable.timed_wait [link_text]]]
[def __cond_timed_wait__ [cond_timed_wait_link `timed_wait()`]]
[template cond_any_wait_link[link_text] [link thread.synchronization.condvar_ref.condition_variable_any.wait [link_text]]]
[def __cond_any_wait__ [cond_any_wait_link `wait()`]]
[template cond_any_timed_wait_link[link_text] [link thread.synchronization.condvar_ref.condition_variable_any.timed_wait [link_text]]]
[def __cond_any_timed_wait__ [cond_any_timed_wait_link `timed_wait()`]]
[def __blocked__ ['blocked]]
[include overview.qbk]
[include changes.qbk]
[include thread_ref.qbk]
[section:synchronization Synchronization]
[include mutex_concepts.qbk]
[include mutexes.qbk]
[include condition_variables.qbk]
[include once.qbk]
[include barrier.qbk]
[include futures.qbk]
[endsect]
[include tss.qbk]
[include time.qbk]
[include acknowledgements.qbk]

207
doc/thread_pool.html Normal file
View File

@@ -0,0 +1,207 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Header &lt;boost/thread/thread_pool.hpp&gt;</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Header &lt;<a href="../../../boost/thread/thread_pool.hpp">boost/thread/thread_pool.hpp</a>&gt;</h2>
</td>
</tr>
</table>
<hr>
<h2>Contents</h2>
<dl class="page-index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#classes">Classes</a></dt>
<dl class="page-index">
<dt><a href="#class-thread_pool">Class <code>thread_pool</code></a></dt>
<dl class="page-index">
<dt><a href="#class-thread_pool-synopsis">Class <code>thread_pool</code> synopsis</a></dt>
<dt><a href="#class-thread_pool-ctors">Class <code>thread_pool</code> constructors and destructor</a></dt>
<dt><a href="#class-thread_pool-modifiers">Class <code>thread_pool</code> modifier functions</a></dt>
</dl>
</dl>
<dt><a href="#examples">Example(s)</a></dt>
</dl>
<hr>
<h2><a name="introduction"></a>Introduction</h2>
<p>Include the header &lt;<a href="../../../boost/thread/thread_pool.hpp">boost/thread/thread_pool.hpp</a>&gt;
to define the <a href="#class-thread_pool">thread_pool</a> class.</p>
<h2><a name="classes"></a>Classes</h2>
<h3><a name="class-thread_pool"></a>Class <code>thread_pool</code></h3>
<p>The <tt>thread_pool</tt> class provides&nbsp;an interface for&nbsp;running
jobs on a dynamically managed set&nbsp;of worker threads called a pool.&nbsp;
When a job is added, it can execute on any&nbsp;available thread in the pool.&nbsp;
This class controls&nbsp;both the maximum and minimum number of threads&nbsp;in
the pool.&nbsp; If a thread in the pool is sitting idle&nbsp;for a period&nbsp;of
time, it&nbsp;will exit unless by exiting the number of threads would dip below
the minimum. Thread pools provide an optimization over creating a new thread
for each job since the pool can often remove the overhead of thread creation.</p>
<h4><a name="class-thread_pool-synopsis"></a>Class <code>thread_pool</code> synopsis</h4>
<pre>
namespace boost
{
class thread_pool : <a href="../../utility/utility.htm#Class noncopyable">boost::noncopyable</a> // Exposition only.
// Class thread meets the <a href="overview.html#non-copyable">NonCopyable</a> requirement.
{
public:
thread_pool(int max_threads=std::numeric_limits&lt;int&gt;::max(),
int min_threads=0,
int timeout_secs=5);
~thread_pool();
void add(const boost::function0&lt;void&gt; &amp;job);
void join();
void cancel();
void detach();
};
};
</pre>
<h4><a name="class-spec-ctors"></a>Class <code>thread_pool</code> constructors and destructor</h4>
<pre>
thread_pool(int max_threads=std::numeric_limits&lt;int&gt;::max(),
int min_threads=0,
int timeout_secs=5);
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Constructs a thread pool object and starts min_threads threads
running in the pool.</dt>
</dl>
<pre>
~thread_pool();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Calls join() if neither join() nor detach() were called
previously for this thread_pool.&nbsp; If detach() was not called, destroys all
resources associated with the threads in the pool and with the queue of jobs
still waiting to be executed.</dt>
</dl>
<h4><a name="class-spec-modifiers"></a>Class <code>thread_pool</code> modifier
functions</h4>
<pre>
void add(const boost::function0&lt;void&gt;&amp; job);
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Adds <tt>job</tt> to the <tt>thread_pool</tt> object's list of
jobs waiting to be executed.&nbsp; If any threads in the pool are idle, the job
will be execute as soon as the idle thread is scheduled by the operating
system.&nbsp; If no threads are idle and the number of threads in the pool is
less than the maximum number provided to the constructor, an additional thread
is created and added to the pool.&nbsp; That new thread will execute this job
as soon as it is scheduled by the operating system.&nbsp; If no threads are
idle and&nbsp;the thread count is at the maximum, this job will be queued until
a thread becomes available.&nbsp; Currently, queued jobs are processed in FIFO
order.</dt>
<dt><b>Throws:</b> std::runtime_error if join() or detach() have
previously been called for this thread_pool object.</dt>
</dl>
<pre>
void detach();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Relinquishes control of the pool of threads by this thread_pool
object.&nbsp; Any threads in the pool will continue to run and continue to
process any queued jobs, but no new threads will be created, and any subsequent
attempts to add new jobs will result in an exception.</dt>
<dt><b>Throws:</b> std::runtime_error if join()&nbsp;has previously
been called for this thread_pool object.</dt>
</dl>
<pre>
void cancel();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Removes all queued jobs from the thread_pool's internal queue,
and calls cancel() on all boost::thread objects in the pool.&nbsp; The specific
behavior of those threads will be dictated by their cancellation behavior - the
pool threads may be executing a user's job that deferrs cancellation, for
example.</dt>
<dt><b>Throws:</b> std::runtime_error if join() or detach() have
previously been called for this thread_pool object.</dt>
<dt><b>Note:</b> for the current version (1.27.0) of Boost.Threads, thread::cancel() is
not provided.&nbsp; This function -will- clear out all queued jobs, but any
currently executing jobs will not be cancelled.</dt>
</dl>
<pre>
void join();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Waits until all queued jobs are completed by the thread pool,
and then join()s will all of the threads in the pool.&nbsp; When join()
returns, no running threads will remain in the pool, and this object is invalid
for anything except destruction.&nbsp; Any calls to cancel(), join(), detach(),
or add() will result in an exception.</dt>
</dl>
<h2><a name="examples"></a>Example(s)</h2>
<pre>
#include &lt;boost/thread/thread_pool.hpp&gt;
#include &lt;boost/thread/mutex.hpp&gt;
#include &lt;iostream&gt;
boost::mutex io_mutex;
class job_adapter {
public:
job_adapter(void (*func)(int), int param) :
_func(func), _param(param){ }
void operator()() const { _func(_param); }
private:
void (*_func)(int);
int _param;
};
void simple_job(int param)
{
boost::mutex::scoped_lock l(io_mutex);
std::cout &lt;&lt; param &lt;&lt; " squared is " &lt;&lt; (param*param) &lt;&lt; "\n";
}
int main(int argc, char* argv[])
{
boost::thread_pool tp;
for (int i = 1; i &lt;= 10; ++i)
tp.add(simple_job);
tp.join();
return 0;
}
</pre>
<p>Typical output would be:</p>
<pre>
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
7 squared is 49
6 squared is 36
8 squared is 64
10 squared is 100
9 squared is 81
</pre>
<P>While the jobs are dispatched in the order they are received, the scheduling of
the individual threads in the pool is platform-dependent.</P>
<P>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a>, David Moore 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -1,75 +0,0 @@
[/
(C) Copyright 2007-8 Anthony Williams.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
]
[section:time Date and Time Requirements]
As of Boost 1.35.0, the __boost_thread__ library uses the [link date_time Boost.Date_Time] library for all operations that require a
time out. These include (but are not limited to):
* __sleep__
* __timed_join__
* __cond_timed_wait__
* __timed_lock_ref__
For the overloads that accept an absolute time parameter, an object of type [link thread.time.system_time `boost::system_time`] is
required. Typically, this will be obtained by adding a duration to the current time, obtained with a call to [link
thread.time.get_system_time `boost::get_system_time()`]. e.g.
boost::system_time const timeout=boost::get_system_time() + boost::posix_time::milliseconds(500);
extern bool done;
extern boost::mutex m;
extern boost::condition_variable cond;
boost::unique_lock<boost::mutex> lk(m);
while(!done)
{
if(!cond.timed_wait(lk,timeout))
{
throw "timed out";
}
}
For the overloads that accept a ['TimeDuration] parameter, an object of any type that meets the [link
date_time.posix_time.time_duration Boost.Date_Time Time Duration requirements] can be used, e.g.
boost::this_thread::sleep(boost::posix_time::milliseconds(25));
boost::mutex m;
if(m.timed_lock(boost::posix_time::nanoseconds(100)))
{
// ...
}
[section:system_time Typedef `system_time`]
#include <boost/thread/thread_time.hpp>
typedef boost::posix_time::ptime system_time;
See the documentation for [link date_time.posix_time.ptime_class `boost::posix_time::ptime`] in the Boost.Date_Time library.
[endsect]
[section:get_system_time Non-member function `get_system_time()`]
#include <boost/thread/thread_time.hpp>
system_time get_system_time();
[variablelist
[[Returns:] [The current time.]]
[[Throws:] [Nothing.]]
]
[endsect]
[endsect]

222
doc/tss.html Normal file
View File

@@ -0,0 +1,222 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Header &lt;boost/thread/tss.hpp&gt;</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Header &lt;<a href="../../../boost/thread/tss.hpp">boost/thread/tss.hpp</a>&gt;</h2>
</td>
</tr>
</table>
<hr>
<h2>Contents</h2>
<dl class="page-index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#classes">Classes</a></dt>
<dl class="page-index">
<dt><a href="#class-thread_specific_ptr">Class <code>thread_specific_ptr</code></a></dt>
<dl class="page-index">
<dt><a href="#class-thread_specific_ptr-synopsis">Class <code>thread_specific_ptr</code>
synopsis</a></dt>
<dt><a href="#class-thread_specific_ptr-ctors">Class <code>thread_specific_ptr</code>
constructors and destructor</a></dt>
<dt><a href="#class-thread_specific_ptr-modifiers">Class <code>thread_specific_ptr</code>
modifier functions</a></dt>
<dt><a href="#class-thread_specific_ptr-observers">Class <code>thread_specific_ptr</code>
observer functions</a></dt>
</dl>
</dl>
<dt><a href="#examples">Example(s)</a></dt>
</dl>
<hr>
<h2><a name="introduction"></a>Introduction</h2>
<p>The header &lt;<a href="../../../boost/thread/tss.hpp">boost/thread/tss.hpp</a>&gt;
defines the class <a href="#class-thread_specific_ptr">thread_specific_ptr</a>
which is used to manage data associated with specific thread instances.</p>
<h2><a name="classes"></a>Classes</h2>
<h3><a name="class-thread_specific_ptr"></a>Class <code>thread_specific_ptr</code></h3>
<p>The <code>thread_specific_ptr</code> class defines an interface for using thread
specific storage. Thread specific storage is data associated with individual
threads and is often used to make operations <a href="definitions.html#Thread-safe">thread-safe</a>
that rely on global data.</p>
<p>Template <code>thread_specific_ptr</code> stores a pointer to an object obtained
via <code>new</code> on a thread-by-thread basis and calls a specified cleanup
handler on the contained pointer when the thread terminates. The cleanup handlers
are called in the reverse order of construction of the <code>thread_specific_ptr</code>s,
and for the initial thread are called by the destructor, providing the same
ordering gaurantees as for normal declarations. Each thread initially stores
the null pointer in each <code> thread_specific_ptr</code> instance.</p>
<p>The template <code>thread_specific_ptr</code> is useful in the following cases:</p>
<ul>
<li>An interface was originally written assuming a single thread of control
and is being ported to a multithreaded environment.</li>
<li>Each thread of control invokes sequences of methods that share data that
must be logically accessed through a globally visible access point, but are
physically unique for each thread, instead of being explicitly passed.</li>
</ul>
<h4><a name="class-thread_specific_ptr-synopsis"></a>Class <code>thread_specific_ptr</code>
synopsis</h4>
<pre>
namespace boost
{
template &lt;typename T&gt;
class thread_specific_ptr : private boost::noncopyable // Exposition only.
// Class thread_specific_ptr meets the <a href="overview.html#non-copyable">NonCopyable</a> requirement.
{
public:
thread_specific_ptr();
~thread_specific_ptr();
T* get() const;
T* operator-&gt;() const;
T&amp; operator*() const;
T* release();
void reset(T* p=0);
};
};
</pre>
<h4><a name="class-thread_specific_ptr-ctors"></a>Class <code>thread_specific_ptr</code>
constructors and destructor</h4>
<pre>
thread_specific_ptr();
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> The expression <code>delete get()</code> is well formed.</dt>
<dt><b>Effects:</b> A thread-specific data key is allocated and visible to all
threads in the process. Upon creation, the value <code>NULL</code> will be
associated with the new key in all active threads. Upon thread creation, the
value <code>NULL</code> will be associated with all defined keys in the new
thread. A cleanup method is registered with the key that will call <code>delete</code>
on the value associated with the key for a thread when it exits. When a thread
exits, if a key has a registered cleanup method and the thread has a non-<code>NULL</code>
value associated with that key, the value of the key is set to <code>NULL</code>
and then the cleanup method is called with the previously associated value
as its sole argument. The order in which registered cleanup methods are called
when a thread exits is undefined. If after all the cleanup methods have been
called for all non-<code>NULL</code> values, there are still some non-<code>NULL</code>
values with associated cleanup handlers the result is undefined behavior.</dt>
<dt><b>Throws:</b> <code>boost::thread_resource_error</code> if the necessary
resources can not be obtained.</dt>
<dt><b>Note:</b> There may be an implementation specific limit to the number
of thread specific storage objects that can be created, and this limit may
be small.</dt>
<dt><b>Rationale:</b> The most common need for cleanup will be to call <code>delete</code>
on the associated value. If other forms of cleanup are required the overloaded
constructor should be called instead.</dt>
</dl>
<pre>
thread_specific_ptr(void (*cleanup)(void*));
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> A thread-specific data key is allocated and visible to all
threads in the process. Upon creation, the value <code>NULL</code> will be
associated with the new key in all active threads. Upon thread creation, the
value <code>NULL</code> will be associated with all defined keys in the new
thread. The <code>cleanup</code> method is registered with the key and will
be called for a thread with the value associated with the key for that thread
when it exits. When a thread exits, if a key has a registered cleanup method
and the thread has a non-<code>NULL</code> value associated with that key,
the value of the key is set to <code>NULL</code> and then the cleanup method
is called with the previously associated value as its sole argument. The order
in which registered cleanup methods are called when a thread exits is undefined.
If after all the cleanup methods have been called for all non-<code>NULL</code>
values, there are still some non-<code>NULL</code> values with associated
cleanup handlers the result is undefined behavior.</dt>
<dt><b>Throws:</b> <code>boost::thread_resource_error</code> if the necessary
resources can not be obtained.</dt>
<dt><b>Note:</b> There may be an implementation specific limit to the number
of thread specific storage objects that can be created, and this limit may
be small.</dt>
<dt><b>Rationale:</b> There is the occasional need to register specialized cleanup
methods, or to register no cleanup method at all (done by passing <code>NULL</code>
to this constructor.</dt>
</dl>
<pre>
~thread_specific_ptr();
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> Deletes the thread-specific data key allocated by the constructor.
The thread-specific data values associated with the key need not be <code>NULL</code>.
It is the responsibility of the application to perform any cleanup actions
for data associated with the key.</dt>
<dt><b>Note:</b> Does not destroy any data that may be stored in any thread&#39;s
thread specific storage. For this reason you should not destroy a <code>thread_specific_ptr</code>
object until you are certain there are no threads running that have made use
of its thread specific storage.</dt>
<dt><b>Rationale:</b> Associated data is not cleaned up because registered cleanup
methods need to be run in the thread that allocated the associated data to
be gauranteed to work correctly. There's no safe way to inject the call into
another thread's execution path, making it impossible to call the cleanup
methods safely.</dt>
</dl>
<h4><a name="class-thread_specific_ptr-modifiers"></a>Class <code>thread_specific_ptr</code>
modifier functions</h4>
<pre>
T* release();
</pre>
<dl class="function-semantics">
<dt><b>Postconditions:</b> <code>*this</code> holds the null pointer for the
current thread.</dt>
<dt><b>Returns:</b> <code>this-&gt;get()</code> prior to the call.</dt>
<dt><b>Rationale:</b> This method provides a mechanism for the user to relinquish
control of the data associated with the thread-specific key.</dt>
</dl>
<pre>
void reset(T* p=0);
</pre>
<dl class="function-semantics">
<dt><b>Effects:</b> If <code>this-&gt;get()!= p &amp;&amp; p != NULL</code>
then call the associated cleanup function. </dt>
<dt><b>Postconditions:</b> <code>*this</code> holds the pointer <code> p</code>
for the current thread.</dt>
</dl>
<h4><a name="class-thread_specific_ptr-observers"></a>Class <code>thread_specific_ptr</code>
observer functions</h4>
<pre>
T* get() const;
</pre>
<dl class="function-semantics">
<dt><b>Returns:</b> The object stored in thread specific storage for the current
thread for <code>*this</code>.</dt>
<dt><b>Note:</b> Each thread initially returns 0.</dt>
</dl>
<pre>
T* operator-&gt;() const;
</pre>
<dl class="function-semantics">
<dt><b>Returns:</b> <code>this-&gt;get()</code>.</dt>
</dl>
<pre>
T& operator*() const;
</pre>
<dl class="function-semantics">
<dt><b>Requires:</b> <code>this-&gt;get() != 0</code></dt>
<dt><b>Returns:</b> <code>this-&gt;get()</code>.</dt>
</dl>
<h2><a name="examples"></a>Example(s)</h2>
<p><a href="../example/tss.cpp">libs/thread/example/tss.cpp</a></p>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

View File

@@ -1,184 +0,0 @@
[/
(C) Copyright 2007-8 Anthony Williams.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
]
[section Thread Local Storage]
[heading Synopsis]
Thread local storage allows multi-threaded applications to have a separate instance of a given data item for each thread. Where a
single-threaded application would use static or global data, this could lead to contention, deadlock or data corruption in a
multi-threaded application. One example is the C `errno` variable, used for storing the error code related to functions from the
Standard C library. It is common practice (and required by POSIX) for compilers that support multi-threaded applications to provide
a separate instance of `errno` for each thread, in order to avoid different threads competing to read or update the value.
Though compilers often provide this facility in the form of extensions to the declaration syntax (such as `__declspec(thread)` or
`__thread` annotations on `static` or namespace-scope variable declarations), such support is non-portable, and is often limited in
some way, such as only supporting POD types.
[heading Portable thread-local storage with `boost::thread_specific_ptr`]
`boost::thread_specific_ptr` provides a portable mechanism for thread-local storage that works on all compilers supported by
__boost_thread__. Each instance of `boost::thread_specific_ptr` represents a pointer to an object (such as `errno`) where each
thread must have a distinct value. The value for the current thread can be obtained using the `get()` member function, or by using
the `*` and `->` pointer deference operators. Initially the pointer has a value of `NULL` in each thread, but the value for the
current thread can be set using the `reset()` member function.
If the value of the pointer for the current thread is changed using `reset()`, then the previous value is destroyed by calling the
cleanup routine. Alternatively, the stored value can be reset to `NULL` and the prior value returned by calling the `release()`
member function, allowing the application to take back responsibility for destroying the object.
[heading Cleanup at thread exit]
When a thread exits, the objects associated with each `boost::thread_specific_ptr` instance are destroyed. By default, the object
pointed to by a pointer `p` is destroyed by invoking `delete p`, but this can be overridden for a specific instance of
`boost::thread_specific_ptr` by providing a cleanup routine to the constructor. In this case, the object is destroyed by invoking
`func(p)` where `func` is the cleanup routine supplied to the constructor. The cleanup functions are called in an unspecified
order. If a cleanup routine sets the value of associated with an instance of `boost::thread_specific_ptr` that has already been
cleaned up, that value is added to the cleanup list. Cleanup finishes when there are no outstanding instances of
`boost::thread_specific_ptr` with values.
[section:thread_specific_ptr Class `thread_specific_ptr`]
#include <boost/thread/tss.hpp>
template <typename T>
class thread_specific_ptr
{
public:
thread_specific_ptr();
explicit thread_specific_ptr(void (*cleanup_function)(T*));
~thread_specific_ptr();
T* get() const;
T* operator->() const;
T& operator*() const;
T* release();
void reset(T* new_value=0);
};
[section:default_constructor `thread_specific_ptr();`]
[variablelist
[[Requires:] [`delete this->get()` is well-formed.]]
[[Effects:] [Construct a `thread_specific_ptr` object for storing a pointer to an object of type `T` specific to each thread. The
default `delete`-based cleanup function will be used to destroy any thread-local objects when `reset()` is called, or the thread
exits.]]
[[Throws:] [`boost::thread_resource_error` if an error occurs.]]
]
[endsect]
[section:constructor_with_custom_cleanup `explicit thread_specific_ptr(void (*cleanup_function)(T*));`]
[variablelist
[[Requires:] [`cleanup_function(this->get())` does not throw any exceptions.]]
[[Effects:] [Construct a `thread_specific_ptr` object for storing a pointer to an object of type `T` specific to each thread. The
supplied `cleanup_function` will be used to destroy any thread-local objects when `reset()` is called, or the thread exits.]]
[[Throws:] [`boost::thread_resource_error` if an error occurs.]]
]
[endsect]
[section:destructor `~thread_specific_ptr();`]
[variablelist
[[Effects:] [Calls `this->reset()` to clean up the associated value for the current thread, and destroys `*this`.]]
[[Throws:] [Nothing.]]
]
[note Care needs to be taken to ensure that any threads still running after an instance of `boost::thread_specific_ptr` has been
destroyed do not call any member functions on that instance.]
[endsect]
[section:get `T* get() const;`]
[variablelist
[[Returns:] [The pointer associated with the current thread.]]
[[Throws:] [Nothing.]]
]
[note The initial value associated with an instance of `boost::thread_specific_ptr` is `NULL` for each thread.]
[endsect]
[section:operator_arrow `T* operator->() const;`]
[variablelist
[[Returns:] [`this->get()`]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:operator_star `T& operator*() const;`]
[variablelist
[[Requires:] [`this->get` is not `NULL`.]]
[[Returns:] [`*(this->get())`]]
[[Throws:] [Nothing.]]
]
[endsect]
[section:reset `void reset(T* new_value=0);`]
[variablelist
[[Effects:] [If `this->get()!=new_value` and `this->get()` is non-`NULL`, invoke `delete this->get()` or
`cleanup_function(this->get())` as appropriate. Store `new_value` as the pointer associated with the current thread.]]
[[Postcondition:] [`this->get()==new_value`]]
[[Throws:] [`boost::thread_resource_error` if an error occurs.]]
]
[endsect]
[section:release `T* release();`]
[variablelist
[[Effects:] [Return `this->get()` and store `NULL` as the pointer associated with the current thread without invoking the cleanup
function.]]
[[Postcondition:] [`this->get()==0`]]
[[Throws:] [Nothing.]]
]
[endsect]
[endsect]
[endsect]

110
doc/xtime.html Normal file
View File

@@ -0,0 +1,110 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="../../../boost.css">
<title>Boost.Threads - Header &lt;boost/thread/xtime.hpp&gt;</title>
</head>
<body link="#0000ff" vlink="#800080">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="../../../index.htm"><img height="86" width="277" alt="C++ Boost" src="../../../c++boost.gif" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center">Boost.Threads</h1>
<h2 align="center">Header &lt;<a href="../../../boost/thread/xtime.hpp">boost/thread/xtime.hpp</a>&gt;</h2>
</td>
</tr>
</table>
<hr>
<h2>Contents</h2>
<dl class="page-index">
<dt><a href="#introduction">Introduction</a></dt>
<dt><a href="#values">Values</a></dt>
<dl class="page-index">
<dt><a href="#value-spec">TIME_UTC</a></dt>
</dl>
<dt><a href="#classes">Classes</a></dt>
<dl class="page-index">
<dt><a href="#class-spec">Struct <code>xtime</code></a></dt>
<dl class="page-index">
<dt><a href="#class-xtime-synopsis">Struct <code>xtime</code> synopsis</a></dt>
</dl>
</dl>
<dt><a href="#functions">Functions</a></dt>
<dl class="page-index">
<dt><a href="#function-xtime_get"><code>xtime_get</code></a></dt>
</dl>
<dt><a href="#examples">Example(s)</a></dt>
</dl>
<hr>
<h2><a name="introduction"></a>Introduction</h2>
<p>The header &lt;<a href="../../../boost/thread/xtime.hpp">boost/thread/xtime.hpp</a>&gt;
defines functions and data types used to perform high-resolution time operations.
This is a temporary solution that will be replaced by a more robust time library
once available in Boost.</p>
<h2><a name="values"></a>Values</h2>
<pre><a name="value-spec"></a>
enum
{
TIME_UTC
}
</pre>
<p>The clock type for Coordinated Universal Time (UTC). The epoch for this clock
type is 1970-01-01 00:00:00. This is the only clock type supported by <b>Boost.Threads</b>.</p>
<h2><a name="classes"></a>Classes</h2>
<h3><a name="class-xtime"></a>Struct <code>xtime</code></h3>
<p>The <code>xtime</code> type is used to represent a point on some time scale
or a duration in time. This type may be proposed for the C standard by Markus
Kuhn. <b>Boost.Threads</b> provides only a very minimal implementation of this
proposal and it&#39;s expected that a full implementation (or some other time
library) will be provided in Boost as a separate library, at which time <b>Boost.Threads</b>
will deprecate its implementation.</p>
<h4><a name="class-xtime-synopsis"></a>Struct <code>xtime</code> synopsis</h4>
<pre>
namespace boost
{
struct xtime
{
#if defined(BOOST_NO_INT64_T)
int_fast32_t sec;
#else
int_fast64_t sec;
#endif
int_fast32_t nsec;
};
};
</pre>
<h2><a name="functions"></a>Functions</h2>
<pre>
<a name="function-xtime_get"></a>int xtime_get(struct xtime* xtp, int clock_type);
</pre>
<dl class="function-semantics">
<dt><b>Postconditions:</b> <code>xtp</code> represents the current point in
time as a duration since the epoch specified by the <code> clock_type</code>.</dt>
<dt><b>Returns:</b> <code>clock_type</code> if successful, otherwise 0.</dt>
<dt><b>Note:</b> The resolution is implementation specific. For many implementations
the best resolution of time is far more than one nanosecond, and even when
the resolution is reasonably good, the latency of a call to <code>xtime_get()</code>
may be significant. For maximum portability, avoid durations of less than
one second.</dt>
</dl>
<h2><a name="examples"></a>Example(s)</h2>
<p><a href="../example/xtime.cpp">libs/thread/example/xtime.cpp</a></p>
<hr>
<p>Revised
<!--webbot bot="Timestamp" S-Type="EDITED" S-Format="%d %B, %Y" startspan -->
05 November, 2001
<!--webbot bot="Timestamp" endspan i-checksum="39359" -->
</p>
<p><i>&copy; Copyright <a href="mailto:wekempf@cox.net">William E. Kempf</a> 2001-2002.
All Rights Reserved.</i></p>
<p>Permission to use, copy, modify, distribute and sell this software and its
documentation for any purpose is hereby granted without fee, provided that the
above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation. William E. Kempf
makes no representations about the suitability of this software for any purpose.
It is provided &quot;as is&quot; without express or implied warranty.</p>
</body>
</html>

2
example/.cvsignore Normal file
View File

@@ -0,0 +1,2 @@
bin
*.pdb

34
example/Jamfile Normal file
View File

@@ -0,0 +1,34 @@
# (C) Copyright William E. Kempf 2001. Permission to copy, use, modify, sell and
# distribute this software is granted provided this copyright notice appears
# in all copies. This software is provided "as is" without express or implied
# warranty, and with no claim as to its suitability for any purpose.
# Declare the location of this subproject relative to the root.
subproject libs/thread/example ;
# Include threads.jam for Boost.Threads global build information.
# This greatly simplifies the Jam code needed to configure the build
# for the various Win32 build types.
SEARCH on <module@>threads.jam = $(BOOST_ROOT)/libs/thread/build ;
include <module@>threads.jam ;
template example
## sources ##
: <template>thread_base <lib>../build/boost_thread <lib>../../test/build/unit_test_framework $(threadmon)
## requirements ##
:
## default build ##
: release <runtime-link>static
;
exe monitor : <template>example monitor.cpp ;
exe starvephil : <template>example starvephil.cpp ;
exe tennis : <template>example tennis.cpp ;
exe condition : <template>example condition.cpp ;
exe mutex : <template>example mutex.cpp ;
exe once : <template>example once.cpp ;
exe recursive_mutex : <template>example recursive_mutex.cpp ;
exe thread : <template>example thread.cpp ;
exe thread_group : <template>example thread_group.cpp ;
exe tss : <template>example tss.cpp ;
exe xtime : <template>example xtime.cpp ;

View File

@@ -1,23 +0,0 @@
# Copyright (C) 2001-2003
# William E. Kempf
#
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
project boost/thread/example
: requirements <library>../build//boost_thread <threading>multi
;
exe monitor : monitor.cpp ;
exe starvephil : starvephil.cpp ;
exe tennis : tennis.cpp ;
exe condition : condition.cpp ;
exe mutex : mutex.cpp ;
exe once : once.cpp ;
exe recursive_mutex : recursive_mutex.cpp ;
exe thread : thread.cpp ;
exe thread_group : thread_group.cpp ;
exe tss : tss.cpp ;
exe xtime : xtime.cpp ;

View File

@@ -1,9 +1,3 @@
// Copyright (C) 2001-2003
// William E. Kempf
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <iostream>
#include <vector>
#include <boost/utility.hpp>
@@ -46,18 +40,12 @@ private:
bounded_buffer buf(2);
boost::mutex io_mutex;
void sender() {
int n = 0;
while (n < 1000000) {
buf.send(n);
if(!(n%10000))
{
boost::mutex::scoped_lock io_lock(io_mutex);
std::cout << "sent: " << n << std::endl;
}
++n;
while (n < 100) {
buf.send(n);
std::cout << "sent: " << n << std::endl;
++n;
}
buf.send(-1);
}
@@ -65,25 +53,16 @@ void sender() {
void receiver() {
int n;
do {
n = buf.receive();
if(!(n%10000))
{
boost::mutex::scoped_lock io_lock(io_mutex);
std::cout << "received: " << n << std::endl;
}
n = buf.receive();
std::cout << "received: " << n << std::endl;
} while (n != -1); // -1 indicates end of buffer
buf.send(-1);
}
int main(int, char*[])
{
boost::thread thrd1(&sender);
boost::thread thrd2(&receiver);
boost::thread thrd3(&receiver);
boost::thread thrd4(&receiver);
thrd1.join();
thrd2.join();
thrd3.join();
thrd4.join();
return 0;
}

View File

@@ -1,9 +1,3 @@
// Copyright (C) 2001-2003
// William E. Kempf
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <vector>
#include <iostream>
#include <boost/thread/condition.hpp>
@@ -12,9 +6,9 @@
#include <boost/thread/thread.hpp>
namespace {
const int ITERS = 100;
boost::mutex io_mutex;
} // namespace
const int ITERS = 100;
boost::mutex io_mutex;
}
template <typename M>
class buffer_t

1
example/monitor/Carbon.r Normal file
View File

@@ -0,0 +1 @@
/*

106
example/monitor/monitor.cpp Normal file
View File

@@ -0,0 +1,106 @@
#include <vector>
#include <iostream>
#include <boost/thread/condition.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/thread/thread.hpp>
namespace {
const int ITERS = 100;
boost::mutex io_mutex;
}
template <typename M>
class buffer_t
{
public:
typedef typename M::scoped_lock scoped_lock;
buffer_t(int n)
: p(0), c(0), full(0), buf(n)
{
}
void send(int m)
{
scoped_lock lk(mutex);
while (full == buf.size())
cond.wait(lk);
buf[p] = m;
p = (p+1) % buf.size();
++full;
cond.notify_one();
}
int receive()
{
scoped_lock lk(mutex);
while (full == 0)
cond.wait(lk);
int i = buf[c];
c = (c+1) % buf.size();
--full;
cond.notify_one();
return i;
}
static buffer_t& get_buffer()
{
static buffer_t buf(2);
return buf;
}
static void do_sender_thread()
{
for (int n = 0; n < ITERS; ++n)
{
{
boost::mutex::scoped_lock lock(io_mutex);
std::cout << "sending: " << n << std::endl;
}
get_buffer().send(n);
}
}
static void do_receiver_thread()
{
for (int x=0; x < (ITERS/2); ++x)
{
int n = get_buffer().receive();
{
boost::mutex::scoped_lock lock(io_mutex);
std::cout << "received: " << n << std::endl;
}
}
}
private:
M mutex;
boost::condition cond;
unsigned int p, c, full;
std::vector<int> buf;
};
template <typename M>
void do_test(M* dummy=0)
{
typedef buffer_t<M> buffer_type;
buffer_type::get_buffer();
boost::thread thrd1(&buffer_type::do_receiver_thread);
boost::thread thrd2(&buffer_type::do_receiver_thread);
boost::thread thrd3(&buffer_type::do_sender_thread);
thrd1.join();
thrd2.join();
thrd3.join();
}
void test_buffer()
{
do_test<boost::mutex>();
do_test<boost::recursive_mutex>();
}
int main()
{
test_buffer();
return 0;
}

BIN
example/monitor/monitor.mcp Normal file

Binary file not shown.

View File

@@ -1,9 +1,3 @@
// Copyright (C) 2001-2003
// William E. Kempf
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
#include <iostream>

View File

@@ -1,9 +1,3 @@
// Copyright (C) 2001-2003
// William E. Kempf
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/thread/thread.hpp>
#include <boost/thread/once.hpp>
#include <cassert>
@@ -18,14 +12,14 @@ void init()
void thread_proc()
{
boost::call_once(&init, once);
boost::call_once(&init, once);
}
int main(int argc, char* argv[])
{
boost::thread_group threads;
for (int i=0; i<5; ++i)
threads.create_thread(&thread_proc);
threads.join_all();
assert(value == 1);
boost::thread_group threads;
for (int i=0; i<5; ++i)
threads.create_thread(&thread_proc);
threads.join_all();
assert(value == 1);
}

View File

@@ -1,9 +1,3 @@
// Copyright (C) 2001-2003
// William E. Kempf
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/thread/recursive_mutex.hpp>
#include <boost/thread/thread.hpp>
#include <iostream>

View File

@@ -1,9 +1,3 @@
// Copyright (C) 2001-2003
// William E. Kempf
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/thread.hpp>
@@ -13,8 +7,8 @@
namespace
{
boost::mutex iomx;
} // namespace
boost::mutex iomx;
}
class canteen
{
@@ -45,9 +39,8 @@ public:
boost::mutex::scoped_lock lock(m_mutex);
{
boost::mutex::scoped_lock lock(iomx);
std::cout << "(" << clock()
<< ") Chef: ouch ... make room ... this dish is "
<< "very hot ..." << std::endl;
std::cout << "(" << clock() <<
") Chef: ouch ... make room ... this dish is very hot ..." << std::endl;
}
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
@@ -91,7 +84,7 @@ void chef()
{
boost::mutex::scoped_lock lock(iomx);
std::cout << "(" << clock() << ") Chef: " << chickens
<< " chickens, ready-to-go ..." << std::endl;
<< " chickens, ready-to-go ..." << std::endl;
}
g_canteen.put(chickens);
}
@@ -103,8 +96,7 @@ struct phil
void run() {
{
boost::mutex::scoped_lock lock(iomx);
std::cout << "(" << clock() << ") Phil" << m_id
<< ": starting ..." << std::endl;
std::cout << "(" << clock() << ") Phil" << m_id << ": starting ..." << std::endl;
}
for (;;)
{
@@ -118,13 +110,13 @@ struct phil
{
boost::mutex::scoped_lock lock(iomx);
std::cout << "(" << clock() << ") Phil" << m_id
<< ": gotta eat ..." << std::endl;
<< ": gotta eat ..." << std::endl;
}
g_canteen.get(m_id);
{
boost::mutex::scoped_lock lock(iomx);
std::cout << "(" << clock() << ") Phil" << m_id
<< ": mmm ... that's good ..." << std::endl;
<< ": mmm ... that's good ..." << std::endl;
}
}
}
@@ -137,10 +129,7 @@ struct phil
struct thread_adapt
{
thread_adapt(void (*func)(void*), void* param)
: _func(func), _param(param)
{
}
thread_adapt(void (*func)(void*), void* param) : _func(func), _param(param) { }
int operator()() const
{
_func(_param);
@@ -154,10 +143,7 @@ struct thread_adapt
class thread_adapter
{
public:
thread_adapter(void (*func)(void*), void* param)
: _func(func), _param(param)
{
}
thread_adapter(void (*func)(void*), void* param) : _func(func), _param(param) { }
void operator()() const { _func(_param); }
private:
void (*_func)(void*);

View File

@@ -0,0 +1 @@
/*

View File

@@ -0,0 +1,171 @@
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/xtime.hpp>
#include <iostream>
#include <time.h>
namespace
{
boost::mutex iomx;
}
class canteen
{
public:
canteen() : m_chickens(0) { }
void get(int id)
{
boost::mutex::scoped_lock lock(m_mutex);
while (m_chickens == 0)
{
{
boost::mutex::scoped_lock lock(iomx);
std::cout << "(" << clock() << ") Phil" << id <<
": wot, no chickens? I'll WAIT ..." << std::endl;
}
m_condition.wait(lock);
}
{
boost::mutex::scoped_lock lock(iomx);
std::cout << "(" << clock() << ") Phil" << id <<
": those chickens look good ... one please ..." << std::endl;
}
m_chickens--;
}
void put(int value)
{
boost::mutex::scoped_lock lock(m_mutex);
{
boost::mutex::scoped_lock lock(iomx);
std::cout << "(" << clock() <<
") Chef: ouch ... make room ... this dish is very hot ..." << std::endl;
}
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
xt.sec += 3;
boost::thread::sleep(xt);
m_chickens += value;
{
boost::mutex::scoped_lock lock(iomx);
std::cout << "(" << clock() <<
") Chef: more chickens ... " << m_chickens <<
" now available ... NOTIFYING ..." << std::endl;
}
m_condition.notify_all();
}
private:
boost::mutex m_mutex;
boost::condition m_condition;
int m_chickens;
};
canteen g_canteen;
void chef()
{
const int chickens = 4;
{
boost::mutex::scoped_lock lock(iomx);
std::cout << "(" << clock() << ") Chef: starting ..." << std::endl;
}
for (;;)
{
{
boost::mutex::scoped_lock lock(iomx);
std::cout << "(" << clock() << ") Chef: cooking ..." << std::endl;
}
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
xt.sec += 2;
boost::thread::sleep(xt);
{
boost::mutex::scoped_lock lock(iomx);
std::cout << "(" << clock() << ") Chef: " << chickens
<< " chickens, ready-to-go ..." << std::endl;
}
g_canteen.put(chickens);
}
}
struct phil
{
phil(int id) : m_id(id) { }
void run() {
{
boost::mutex::scoped_lock lock(iomx);
std::cout << "(" << clock() << ") Phil" << m_id << ": starting ..." << std::endl;
}
for (;;)
{
if (m_id > 0)
{
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
xt.sec += 3;
boost::thread::sleep(xt);
}
{
boost::mutex::scoped_lock lock(iomx);
std::cout << "(" << clock() << ") Phil" << m_id
<< ": gotta eat ..." << std::endl;
}
g_canteen.get(m_id);
{
boost::mutex::scoped_lock lock(iomx);
std::cout << "(" << clock() << ") Phil" << m_id
<< ": mmm ... that's good ..." << std::endl;
}
}
}
static void do_thread(void* param) {
static_cast<phil*>(param)->run();
}
int m_id;
};
struct thread_adapt
{
thread_adapt(void (*func)(void*), void* param) : _func(func), _param(param) { }
int operator()() const
{
_func(_param);
return 0;
}
void (*_func)(void*);
void* _param;
};
class thread_adapter
{
public:
thread_adapter(void (*func)(void*), void* param) : _func(func), _param(param) { }
void operator()() const { _func(_param); }
private:
void (*_func)(void*);
void* _param;
};
int main(int argc, char* argv[])
{
boost::thread thrd_chef(&chef);
phil p[] = { phil(0), phil(1), phil(2), phil(3), phil(4) };
boost::thread thrd_phil0(thread_adapter(&phil::do_thread, &p[0]));
boost::thread thrd_phil1(thread_adapter(&phil::do_thread, &p[1]));
boost::thread thrd_phil2(thread_adapter(&phil::do_thread, &p[2]));
boost::thread thrd_phil3(thread_adapter(&phil::do_thread, &p[3]));
boost::thread thrd_phil4(thread_adapter(&phil::do_thread, &p[4]));
thrd_chef.join();
thrd_phil0.join();
thrd_phil1.join();
thrd_phil2.join();
thrd_phil3.join();
thrd_phil4.join();
return 0;
}

Binary file not shown.

View File

@@ -1,9 +1,3 @@
// Copyright (C) 2001-2003
// William E. Kempf
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/thread.hpp>
@@ -55,10 +49,7 @@ void player(void* param)
{
cond.wait(lock);
if (state == other)
{
std::cout << "---" << player_name(active)
<< ": Spurious wakeup!" << std::endl;
}
std::cout << "---" << player_name(active) << ": Spurious wakeup!" << std::endl;
} while (state == other);
}
@@ -69,10 +60,7 @@ void player(void* param)
struct thread_adapt
{
thread_adapt(void (*func)(void*), void* param)
: _func(func), _param(param)
{
}
thread_adapt(void (*func)(void*), void* param) : _func(func), _param(param) { }
int operator()() const
{
_func(_param);
@@ -86,10 +74,7 @@ struct thread_adapt
class thread_adapter
{
public:
thread_adapter(void (*func)(void*), void* param)
: _func(func), _param(param)
{
}
thread_adapter(void (*func)(void*), void* param) : _func(func), _param(param) { }
void operator()() const { _func(_param); }
private:
void (*_func)(void*);
@@ -112,7 +97,7 @@ int main(int argc, char* argv[])
std::cout << "---Noise ON..." << std::endl;
}
for (int i = 0; i < 1000000000; ++i)
for (int i = 0; i < 1000000; ++i)
cond.notify_all();
{

1
example/tennis/Carbon.r Normal file
View File

@@ -0,0 +1 @@
/*

120
example/tennis/tennis.cpp Normal file
View File

@@ -0,0 +1,120 @@
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/xtime.hpp>
#include <iostream>
#if defined(BOOST_HAS_WINTHREADS)
# include <windows.h>
# include <process.h>
#endif
enum game_state
{
START,
PLAYER_A,
PLAYER_B,
GAME_OVER,
ONE_PLAYER_GONE,
BOTH_PLAYERS_GONE
};
int state;
boost::mutex mutex;
boost::condition cond;
char* player_name(int state)
{
if (state == PLAYER_A)
return "PLAYER-A";
if (state == PLAYER_B)
return "PLAYER-B";
throw "bad player";
return 0;
}
void player(void* param)
{
boost::mutex::scoped_lock lock(mutex);
int active = (int)param;
int other = active == PLAYER_A ? PLAYER_B : PLAYER_A;
while (state < GAME_OVER)
{
std::cout << player_name(active) << ": Play." << std::endl;
state = other;
cond.notify_all();
do
{
cond.wait(lock);
if (state == other)
std::cout << "---" << player_name(active) << ": Spurious wakeup!" << std::endl;
} while (state == other);
}
++state;
std::cout << player_name(active) << ": Gone." << std::endl;
cond.notify_all();
}
struct thread_adapt
{
thread_adapt(void (*func)(void*), void* param) : _func(func), _param(param) { }
int operator()() const
{
_func(_param);
return 0;
}
void (*_func)(void*);
void* _param;
};
class thread_adapter
{
public:
thread_adapter(void (*func)(void*), void* param) : _func(func), _param(param) { }
void operator()() const { _func(_param); }
private:
void (*_func)(void*);
void* _param;
};
int main(int argc, char* argv[])
{
state = START;
boost::thread thrda(thread_adapter(&player, (void*)PLAYER_A));
boost::thread thrdb(thread_adapter(&player, (void*)PLAYER_B));
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
xt.sec += 1;
boost::thread::sleep(xt);
{
boost::mutex::scoped_lock lock(mutex);
std::cout << "---Noise ON..." << std::endl;
}
for (int i = 0; i < 1000000; ++i)
cond.notify_all();
{
boost::mutex::scoped_lock lock(mutex);
std::cout << "---Noise OFF..." << std::endl;
state = GAME_OVER;
cond.notify_all();
do
{
cond.wait(lock);
} while (state != BOTH_PLAYERS_GONE);
}
std::cout << "GAME OVER" << std::endl;
thrda.join();
thrdb.join();
return 0;
}

BIN
example/tennis/tennis.mcp Normal file

Binary file not shown.

View File

@@ -1,35 +1,29 @@
// Copyright (C) 2001-2003
// William E. Kempf
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/thread/thread.hpp>
#include <boost/thread/xtime.hpp>
#include <iostream>
struct thread_alarm
{
thread_alarm(int secs) : m_secs(secs) { }
void operator()()
{
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
xt.sec += m_secs;
thread_alarm(int secs) : m_secs(secs) { }
void operator()()
{
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
xt.sec += m_secs;
boost::thread::sleep(xt);
boost::thread::sleep(xt);
std::cout << "alarm sounded..." << std::endl;
}
std::cout << "alarm sounded..." << std::endl;
}
int m_secs;
int m_secs;
};
int main(int argc, char* argv[])
{
int secs = 5;
std::cout << "setting alarm for 5 seconds..." << std::endl;
thread_alarm alarm(secs);
boost::thread thrd(alarm);
thrd.join();
int secs = 5;
std::cout << "setting alarm for 5 seconds..." << std::endl;
thread_alarm alarm(secs);
boost::thread thrd(alarm);
thrd.join();
}

View File

@@ -1,9 +1,3 @@
// Copyright (C) 2001-2003
// William E. Kempf
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/thread/thread.hpp>
#include <iostream>
@@ -12,14 +6,14 @@ boost::mutex mutex;
void increment_count()
{
boost::mutex::scoped_lock lock(mutex);
std::cout << "count = " << ++count << std::endl;
boost::mutex::scoped_lock lock(mutex);
std::cout << "count = " << ++count << std::endl;
}
int main(int argc, char* argv[])
{
boost::thread_group threads;
for (int i = 0; i < 10; ++i)
threads.create_thread(&increment_count);
threads.join_all();
boost::thread_group threads;
for (int i = 0; i < 10; ++i)
threads.create_thread(&increment_count);
threads.join_all();
}

View File

@@ -1,9 +1,3 @@
// Copyright (C) 2001-2003
// William E. Kempf
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/thread/thread.hpp>
#include <boost/thread/tss.hpp>
#include <cassert>
@@ -12,25 +6,25 @@ boost::thread_specific_ptr<int> value;
void increment()
{
int* p = value.get();
++*p;
int* p = value.get();
++*p;
}
void thread_proc()
{
value.reset(new int(0)); // initialize the thread's storage
for (int i=0; i<10; ++i)
{
increment();
int* p = value.get();
assert(*p == i+1);
}
value.reset(new int(0)); // initialize the thread's storage
for (int i=0; i<10; ++i)
{
increment();
int* p = value.get();
assert(*p == i+1);
}
}
int main(int argc, char* argv[])
{
boost::thread_group threads;
for (int i=0; i<5; ++i)
threads.create_thread(&thread_proc);
threads.join_all();
boost::thread_group threads;
for (int i=0; i<5; ++i)
threads.create_thread(&thread_proc);
threads.join_all();
}

View File

@@ -1,16 +1,10 @@
// Copyright (C) 2001-2003
// William E. Kempf
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/thread/thread.hpp>
#include <boost/thread/xtime.hpp>
int main(int argc, char* argv[])
{
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
xt.sec += 1;
boost::thread::sleep(xt); // Sleep for 1 second
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
xt.sec += 1;
boost::thread::sleep(xt); // Sleep for 1 second
}

View File

@@ -1,26 +0,0 @@
// Copyright (C) 2001-2003
// William E. Kempf
// (C) Copyright 2008-9 Anthony Williams
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See www.boost.org/libs/thread for documentation.
#if !defined(BOOST_THREAD_WEK01082003_HPP)
#define BOOST_THREAD_WEK01082003_HPP
#include <boost/thread/thread.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/exceptions.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/once.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/thread/tss.hpp>
#include <boost/thread/thread_time.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/thread/future.hpp>
#endif

View File

@@ -1,64 +1,38 @@
// Copyright (C) 2002-2003
// Copyright (C) 2002
// David Moore, William E. Kempf
// Copyright (C) 2007-8 Anthony Williams
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation. William E. Kempf makes no representations
// about the suitability of this software for any purpose.
// It is provided "as is" without express or implied warranty.
#ifndef BOOST_BARRIER_JDM030602_HPP
#define BOOST_BARRIER_JDM030602_HPP
#include <boost/thread/detail/config.hpp>
#include <boost/throw_exception.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <string>
#include <stdexcept>
#include <boost/thread/condition.hpp>
#include <boost/config/abi_prefix.hpp>
namespace boost {
namespace boost
class barrier
{
public:
barrier(unsigned int count);
~barrier();
class barrier
{
public:
barrier(unsigned int count)
: m_threshold(count), m_count(count), m_generation(0)
{
if (count == 0)
boost::throw_exception(std::invalid_argument("count cannot be zero."));
}
bool wait()
{
boost::mutex::scoped_lock lock(m_mutex);
unsigned int gen = m_generation;
if (--m_count == 0)
{
m_generation++;
m_count = m_threshold;
m_cond.notify_all();
return true;
}
bool wait();
while (gen == m_generation)
m_cond.wait(lock);
return false;
}
private:
mutex m_mutex;
condition_variable m_cond;
unsigned int m_threshold;
unsigned int m_count;
unsigned int m_generation;
};
private:
mutex m_mutex;
condition m_cond;
unsigned int m_threshold;
unsigned int m_count;
unsigned int m_generation;
};
} // namespace boost
#include <boost/config/abi_suffix.hpp>
#endif

View File

@@ -1,16 +1,170 @@
#ifndef BOOST_THREAD_CONDITION_HPP
#define BOOST_THREAD_CONDITION_HPP
// (C) Copyright 2007 Anthony Williams
// Copyright (C) 2001
// William E. Kempf
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation. William E. Kempf makes no representations
// about the suitability of this software for any purpose.
// It is provided "as is" without express or implied warranty.
#include <boost/thread/condition_variable.hpp>
namespace boost
{
typedef condition_variable_any condition;
}
#ifndef BOOST_CONDITION_WEK070601_HPP
#define BOOST_CONDITION_WEK070601_HPP
#include <boost/config.hpp>
#ifndef BOOST_HAS_THREADS
# error Thread support is unavailable!
#endif
#include <boost/thread/exceptions.hpp>
#include <boost/utility.hpp>
#include <boost/thread/detail/lock.hpp>
#if defined(BOOST_HAS_PTHREADS)
# include <pthread.h>
#elif defined(BOOST_HAS_MPTASKS)
# include "scoped_critical_region.hpp"
#endif
namespace boost {
struct xtime;
class condition : private noncopyable
{
public:
condition();
~condition();
void notify_one();
void notify_all();
template <typename L>
void wait(L& lock)
{
if (!lock)
throw lock_error();
do_wait(lock.m_mutex);
}
template <typename L, typename Pr>
void wait(L& lock, Pr pred)
{
if (!lock)
throw lock_error();
while (!pred())
do_wait(lock.m_mutex);
}
template <typename L>
bool timed_wait(L& lock, const xtime& xt)
{
if (!lock)
throw lock_error();
return do_timed_wait(lock.m_mutex, xt);
}
template <typename L, typename Pr>
bool timed_wait(L& lock, const xtime& xt, Pr pred)
{
if (!lock)
throw lock_error();
while (!pred())
{
if (!do_timed_wait(lock.m_mutex, xt))
return false;
}
return true;
}
private:
template <typename M>
void do_wait(M& mutex)
{
#if (defined(BOOST_HAS_WINTHREADS) || defined(BOOST_HAS_MPTASKS))
enter_wait();
#endif
typedef detail::thread::lock_ops<M> lock_ops;
typename lock_ops::lock_state state;
lock_ops::unlock(mutex, state);
#if defined(BOOST_HAS_PTHREADS)
do_wait(state.pmutex);
#elif (defined(BOOST_HAS_WINTHREADS) || defined(BOOST_HAS_MPTASKS))
do_wait();
#endif
lock_ops::lock(mutex, state);
}
template <typename M>
bool do_timed_wait(M& mutex, const xtime& xt)
{
#if (defined(BOOST_HAS_WINTHREADS) || defined(BOOST_HAS_MPTASKS))
enter_wait();
#endif
typedef detail::thread::lock_ops<M> lock_ops;
typename lock_ops::lock_state state;
lock_ops::unlock(mutex, state);
bool ret = false;
#if defined(BOOST_HAS_PTHREADS)
ret = do_timed_wait(xt, state.pmutex);
#elif (defined(BOOST_HAS_WINTHREADS) || defined(BOOST_HAS_MPTASKS))
ret = do_timed_wait(xt);
#endif
lock_ops::lock(mutex, state);
return ret;
}
#if (defined(BOOST_HAS_WINTHREADS) || defined(BOOST_HAS_MPTASKS))
void enter_wait();
void do_wait();
bool do_timed_wait(const xtime& xt);
#elif defined(BOOST_HAS_PTHREADS)
void do_wait(pthread_mutex_t* pmutex);
bool do_timed_wait(const xtime& xt, pthread_mutex_t* pmutex);
#endif
#if defined(BOOST_HAS_WINTHREADS)
void* m_gate;
void* m_queue;
void* m_mutex;
unsigned m_gone; // # threads that timed out and never made it to the m_queue
unsigned long m_blocked; // # threads m_blocked m_waiting for the condition
unsigned m_waiting; // # threads m_waiting no longer m_waiting for the condition but still
// m_waiting to be removed from the m_queue
#elif defined(BOOST_HAS_PTHREADS)
pthread_cond_t m_condition;
#elif defined(BOOST_HAS_MPTASKS)
MPSemaphoreID m_gate;
MPSemaphoreID m_queue;
threads::mac::detail::scoped_critical_region m_mutex;
threads::mac::detail::scoped_critical_region m_mutex_mutex;
unsigned m_gone; // # threads that timed out and never made it to the m_queue
unsigned long m_blocked; // # threads m_blocked m_waiting for the condition
unsigned m_waiting; // # threads m_waiting no longer m_waiting for the condition but still
// m_waiting to be removed from the m_queue
#endif
};
} // namespace boost
// Change Log:
// 8 Feb 01 WEKEMPF Initial version.
// 22 May 01 WEKEMPF Modified to use xtime for time outs.
// 23 May 01 WEKEMPF Removed "duration" timed_waits, as they are too difficult
// to use with spurious wakeups.
#endif // BOOST_CONDITION_WEK070601_HPP

View File

@@ -1,21 +0,0 @@
#ifndef BOOST_THREAD_CONDITION_VARIABLE_HPP
#define BOOST_THREAD_CONDITION_VARIABLE_HPP
// condition_variable.hpp
//
// (C) Copyright 2007 Anthony Williams
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/thread/detail/platform.hpp>
#if defined(BOOST_THREAD_PLATFORM_WIN32)
#include <boost/thread/win32/condition_variable.hpp>
#elif defined(BOOST_THREAD_PLATFORM_PTHREAD)
#include <boost/thread/pthread/condition_variable.hpp>
#else
#error "Boost threads unavailable on this platform"
#endif
#endif

View File

@@ -1,100 +0,0 @@
// Copyright (C) 2001-2003
// William E. Kempf
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_THREAD_CONFIG_WEK01032003_HPP
#define BOOST_THREAD_CONFIG_WEK01032003_HPP
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#if BOOST_WORKAROUND(__BORLANDC__, < 0x600)
# pragma warn -8008 // Condition always true/false
# pragma warn -8080 // Identifier declared but never used
# pragma warn -8057 // Parameter never used
# pragma warn -8066 // Unreachable code
#endif
#include "platform.hpp"
// provided for backwards compatibility, since this
// macro was used for several releases by mistake.
#if defined(BOOST_THREAD_DYN_DLL)
# define BOOST_THREAD_DYN_LINK
#endif
// compatibility with the rest of Boost's auto-linking code:
#if defined(BOOST_THREAD_DYN_LINK) || defined(BOOST_ALL_DYN_LINK)
# undef BOOST_THREAD_USE_LIB
# define BOOST_THREAD_USE_DLL
#endif
#if defined(BOOST_THREAD_BUILD_DLL) //Build dll
#elif defined(BOOST_THREAD_BUILD_LIB) //Build lib
#elif defined(BOOST_THREAD_USE_DLL) //Use dll
#elif defined(BOOST_THREAD_USE_LIB) //Use lib
#else //Use default
# if defined(BOOST_THREAD_PLATFORM_WIN32)
# if defined(BOOST_MSVC) || defined(BOOST_INTEL_WIN)
//For compilers supporting auto-tss cleanup
//with Boost.Threads lib, use Boost.Threads lib
# define BOOST_THREAD_USE_LIB
# else
//For compilers not yet supporting auto-tss cleanup
//with Boost.Threads lib, use Boost.Threads dll
# define BOOST_THREAD_USE_DLL
# endif
# else
# define BOOST_THREAD_USE_LIB
# endif
#endif
#if defined(BOOST_HAS_DECLSPEC)
# if defined(BOOST_THREAD_BUILD_DLL) //Build dll
# define BOOST_THREAD_DECL __declspec(dllexport)
# elif defined(BOOST_THREAD_USE_DLL) //Use dll
# define BOOST_THREAD_DECL __declspec(dllimport)
# else
# define BOOST_THREAD_DECL
# endif
#else
# define BOOST_THREAD_DECL
#endif // BOOST_HAS_DECLSPEC
//
// Automatically link to the correct build variant where possible.
//
#if !defined(BOOST_ALL_NO_LIB) && !defined(BOOST_THREAD_NO_LIB) && !defined(BOOST_THREAD_BUILD_DLL) && !defined(BOOST_THREAD_BUILD_LIB)
//
// Tell the autolink to link dynamically, this will get undef'ed by auto_link.hpp
// once it's done with it:
//
#if defined(BOOST_THREAD_USE_DLL)
# define BOOST_DYN_LINK
#endif
//
// Set the name of our library, this will get undef'ed by auto_link.hpp
// once it's done with it:
//
#if defined(BOOST_THREAD_LIB_NAME)
# define BOOST_LIB_NAME BOOST_THREAD_LIB_NAME
#else
# define BOOST_LIB_NAME boost_thread
#endif
//
// If we're importing code from a dll, then tell auto_link.hpp about it:
//
// And include the header that does the work:
//
#include <boost/config/auto_link.hpp>
#endif // auto-linking disabled
#endif // BOOST_THREAD_CONFIG_WEK1032003_HPP
// Change Log:
// 22 Jan 05 Roland Schwarz (speedsnail)
// Usage of BOOST_HAS_DECLSPEC macro.
// Default again is static lib usage.
// BOOST_DYN_LINK only defined when autolink included.

View File

@@ -1,39 +1,44 @@
// Copyright (C) 2001-2003
// Copyright (C) 2001
// Mac Murrett
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation. Mac Murrett makes no representations
// about the suitability of this software for any purpose. It is
// provided "as is" without express or implied warranty.
//
// See http://www.boost.org for most recent version including documentation.
#ifndef BOOST_FORCE_CAST_MJM012402_HPP
#define BOOST_FORCE_CAST_MJM012402_HPP
#include <boost/thread/detail/config.hpp>
namespace boost {
namespace detail {
namespace thread {
// force_cast will convert anything to anything.
// general case
template<class Return_Type, class Argument_Type>
inline Return_Type &force_cast(Argument_Type &rSrc)
{
return(*reinterpret_cast<Return_Type *>(&rSrc));
}
{ return(*reinterpret_cast<Return_Type *>(&rSrc)); }
// specialization for const
template<class Return_Type, class Argument_Type>
inline const Return_Type &force_cast(const Argument_Type &rSrc)
{
return(*reinterpret_cast<const Return_Type *>(&rSrc));
}
{ return(*reinterpret_cast<const Return_Type *>(&rSrc)); }
} // namespace thread
} // namespace detail
} // namespace boost
#endif // BOOST_FORCE_CAST_MJM012402_HPP

View File

@@ -0,0 +1,207 @@
// Copyright (C) 2001
// William E. Kempf
//
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation. William E. Kempf makes no representations
// about the suitability of this software for any purpose.
// It is provided "as is" without express or implied warranty.
#ifndef BOOST_XLOCK_WEK070601_HPP
#define BOOST_XLOCK_WEK070601_HPP
#include <boost/utility.hpp>
#include <boost/thread/exceptions.hpp>
namespace boost {
class condition;
struct xtime;
namespace detail { namespace thread {
template <typename Mutex>
class lock_ops : private noncopyable
{
private:
lock_ops() { }
public:
typedef typename Mutex::cv_state lock_state;
static void lock(Mutex& m)
{
m.do_lock();
}
static bool trylock(Mutex& m)
{
return m.do_trylock();
}
static bool timedlock(Mutex& m, const xtime& xt)
{
return m.do_timedlock(xt);
}
static void unlock(Mutex& m)
{
m.do_unlock();
}
static void lock(Mutex& m, lock_state& state)
{
m.do_lock(state);
}
static void unlock(Mutex& m, lock_state& state)
{
m.do_unlock(state);
}
};
template <typename Mutex>
class scoped_lock : private noncopyable
{
public:
typedef Mutex mutex_type;
explicit scoped_lock(Mutex& mx, bool initially_locked=true)
: m_mutex(mx), m_locked(false)
{
if (initially_locked) lock();
}
~scoped_lock()
{
if (m_locked) unlock();
}
void lock()
{
if (m_locked) throw lock_error();
lock_ops<Mutex>::lock(m_mutex);
m_locked = true;
}
void unlock()
{
if (!m_locked) throw lock_error();
lock_ops<Mutex>::unlock(m_mutex);
m_locked = false;
}
bool locked() const { return m_locked; }
operator const void*() const { return m_locked ? this : 0; }
private:
friend class boost::condition;
Mutex& m_mutex;
bool m_locked;
};
template <typename TryMutex>
class scoped_try_lock : private noncopyable
{
public:
typedef TryMutex mutex_type;
explicit scoped_try_lock(TryMutex& mx)
: m_mutex(mx), m_locked(false)
{
try_lock();
}
scoped_try_lock(TryMutex& mx, bool initially_locked)
: m_mutex(mx), m_locked(false)
{
if (initially_locked) lock();
}
~scoped_try_lock()
{
if (m_locked) unlock();
}
void lock()
{
if (m_locked) throw lock_error();
lock_ops<TryMutex>::lock(m_mutex);
m_locked = true;
}
bool try_lock()
{
if (m_locked) throw lock_error();
return (m_locked = lock_ops<TryMutex>::trylock(m_mutex));
}
void unlock()
{
if (!m_locked) throw lock_error();
lock_ops<TryMutex>::unlock(m_mutex);
m_locked = false;
}
bool locked() const { return m_locked; }
operator const void*() const { return m_locked ? this : 0; }
private:
friend class boost::condition;
TryMutex& m_mutex;
bool m_locked;
};
template <typename TimedMutex>
class scoped_timed_lock : private noncopyable
{
public:
typedef TimedMutex mutex_type;
scoped_timed_lock(TimedMutex& mx, const xtime& xt)
: m_mutex(mx), m_locked(false)
{
timed_lock(xt);
}
scoped_timed_lock(TimedMutex& mx, bool initially_locked)
: m_mutex(mx), m_locked(false)
{
if (initially_locked) lock();
}
~scoped_timed_lock()
{
if (m_locked) unlock();
}
void lock()
{
if (m_locked) throw lock_error();
lock_ops<TimedMutex>::lock(m_mutex);
m_locked = true;
}
bool timed_lock(const xtime& xt)
{
if (m_locked) throw lock_error();
return (m_locked = lock_ops<TimedMutex>::timedlock(m_mutex, xt));
}
void unlock()
{
if (!m_locked) throw lock_error();
lock_ops<TimedMutex>::unlock(m_mutex);
m_locked = false;
}
bool locked() const { return m_locked; }
operator const void*() const { return m_locked ? this : 0; }
private:
friend class boost::condition;
TimedMutex& m_mutex;
bool m_locked;
};
} // namespace thread
} // namespace detail
} // namespace boost
// Change Log:
// 8 Feb 01 WEKEMPF Initial version.
// 22 May 01 WEKEMPF Modified to use xtime for time outs.
// 30 Jul 01 WEKEMPF Moved lock types into boost::detail::thread. Renamed some types.
// Added locked() methods.
#endif // BOOST_XLOCK_WEK070601_HPP

View File

@@ -1,60 +0,0 @@
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// (C) Copyright 2007-8 Anthony Williams
#ifndef BOOST_THREAD_MOVE_HPP
#define BOOST_THREAD_MOVE_HPP
#ifndef BOOST_NO_SFINAE
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_convertible.hpp>
#endif
#include <boost/config/abi_prefix.hpp>
namespace boost
{
namespace detail
{
template<typename T>
struct thread_move_t
{
T& t;
explicit thread_move_t(T& t_):
t(t_)
{}
T& operator*() const
{
return t;
}
T* operator->() const
{
return &t;
}
private:
void operator=(thread_move_t&);
};
}
#ifndef BOOST_NO_SFINAE
template<typename T>
typename enable_if<boost::is_convertible<T&,detail::thread_move_t<T> >, detail::thread_move_t<T> >::type move(T& t)
{
return detail::thread_move_t<T>(t);
}
#endif
template<typename T>
detail::thread_move_t<T> move(detail::thread_move_t<T> t)
{
return t;
}
}
#include <boost/config/abi_suffix.hpp>
#endif

View File

@@ -1,71 +0,0 @@
// Copyright 2006 Roland Schwarz.
// (C) Copyright 2007 Anthony Williams
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// This work is a reimplementation along the design and ideas
// of William E. Kempf.
#ifndef BOOST_THREAD_RS06040501_HPP
#define BOOST_THREAD_RS06040501_HPP
// fetch compiler and platform configuration
#include <boost/config.hpp>
// insist on threading support being available:
#include <boost/config/requires_threads.hpp>
// choose platform
#if defined(linux) || defined(__linux) || defined(__linux__)
# define BOOST_THREAD_LINUX
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
# define BOOST_THREAD_BSD
#elif defined(sun) || defined(__sun)
# define BOOST_THREAD_SOLARIS
#elif defined(__sgi)
# define BOOST_THREAD_IRIX
#elif defined(__hpux)
# define BOOST_THREAD_HPUX
#elif defined(__CYGWIN__)
# define BOOST_THREAD_CYGWIN
#elif (defined(_WIN32) || defined(__WIN32__) || defined(WIN32)) && !defined(BOOST_DISABLE_WIN32)
# define BOOST_THREAD_WIN32
#elif defined(__BEOS__)
# define BOOST_THREAD_BEOS
#elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
# define BOOST_THREAD_MACOS
#elif defined(__IBMCPP__) || defined(_AIX)
# define BOOST_THREAD_AIX
#elif defined(__amigaos__)
# define BOOST_THREAD_AMIGAOS
#elif defined(__QNXNTO__)
# define BOOST_THREAD_QNXNTO
#elif defined(unix) || defined(__unix) || defined(_XOPEN_SOURCE) || defined(_POSIX_SOURCE)
# if defined(BOOST_HAS_PTHREADS) && !defined(BOOST_THREAD_POSIX)
# define BOOST_THREAD_POSIX
# endif
#endif
// For every supported platform add a new entry into the dispatch table below.
// BOOST_THREAD_POSIX is tested first, so on platforms where posix and native
// threading is available, the user may choose, by defining BOOST_THREAD_POSIX
// in her source. If a platform is known to support pthreads and no native
// port of boost_thread is available just specify "pthread" in the
// dispatcher table. If there is no entry for a platform but pthreads is
// available on the platform, pthread is choosen as default. If nothing is
// available the preprocessor will fail with a diagnostic message.
#if defined(BOOST_THREAD_POSIX)
# define BOOST_THREAD_PLATFORM_PTHREAD
#else
# if defined(BOOST_THREAD_WIN32)
# define BOOST_THREAD_PLATFORM_WIN32
# elif defined(BOOST_HAS_PTHREADS)
# define BOOST_THREAD_PLATFORM_PTHREAD
# else
# error "Sorry, no boost threads are available for this platform."
# endif
#endif
#endif // BOOST_THREAD_RS06040501_HPP

View File

@@ -0,0 +1,334 @@
// Copyright (C) 2002
// David Moore
//
// Original scoped_lock implementation
// Copyright (C) 2001
// William E. Kempf
//
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation. David Moore makes no representations
// about the suitability of this software for any purpose.
// It is provided "as is" without express or implied warranty.
#ifndef BOOST_XRWLOCK_JDM031002_HPP
#define BOOST_XRWLOCK_JDM031002_HPP
#include <boost/utility.hpp>
#include <boost/thread/exceptions.hpp>
namespace boost {
class condition;
struct xtime;
typedef enum
{
NO_LOCK=0,
SHARED_LOCK=1,
EXCL_LOCK=2
} rw_lock_state;
namespace detail { namespace thread {
template <typename Mutex>
class rw_lock_ops : private noncopyable
{
private:
rw_lock_ops() { }
public:
static void wrlock(Mutex& m)
{
m.do_wrlock();
}
static void rdlock(Mutex& m)
{
m.do_rdlock();
}
static void wrunlock(Mutex& m)
{
m.do_wrunlock();
}
static void rdunlock(Mutex &m)
{
m.do_rdunlock();
}
static bool try_wrlock(Mutex &m)
{
return m.do_try_wrlock();
}
static bool try_rdlock(Mutex &m)
{
return m.do_try_rdlock();
}
static bool timed_wrlock(Mutex &m,const xtime &xt)
{
return m.do_timed_wrlock(xt);
}
static bool timed_rdlock(Mutex &m,const xtime &xt)
{
return m.do_timed_rdlock(xt);
}
};
template <typename RWMutex>
class scoped_rw_lock : private noncopyable
{
public:
typedef RWMutex mutex_type;
explicit scoped_rw_lock(RWMutex& mx, rw_lock_state initial_state=SHARED_LOCK)
: m_mutex(mx), m_locked(NO_LOCK)
{
if(initial_state == SHARED_LOCK)
rdlock();
else if(initial_state == EXCL_LOCK)
wrlock();
}
~scoped_rw_lock()
{
if(m_locked != NO_LOCK)
unlock();
}
void rdlock()
{
if (m_locked != NO_LOCK) throw lock_error();
rw_lock_ops<RWMutex>::rdlock(m_mutex);
m_locked = SHARED_LOCK;
}
void wrlock()
{
if(m_locked != NO_LOCK) throw lock_error();
rw_lock_ops<RWMutex>::wrlock(m_mutex);
m_locked = EXCL_LOCK;
}
void unlock()
{
if (m_locked == NO_LOCK) throw lock_error();
if(m_locked == SHARED_LOCK)
rw_lock_ops<RWMutex>::rdunlock(m_mutex);
else
rw_lock_ops<RWMutex>::wrunlock(m_mutex);
m_locked = NO_LOCK;
}
bool locked() const
{
return m_locked != NO_LOCK;
}
operator const void*() const
{
return (m_locked != NO_LOCK) ? this : 0;
}
rw_lock_state state() const
{
return m_locked;
}
private:
RWMutex& m_mutex;
rw_lock_state m_locked;
};
template <typename TryRWMutex>
class scoped_try_rw_lock : private noncopyable
{
public:
typedef TryRWMutex mutex_type;
explicit scoped_try_rw_lock(TryRWMutex& mx)
: m_mutex(mx), m_locked(NO_LOCK)
{
try_rdlock();
}
scoped_try_rw_lock(TryRWMutex& mx, rw_lock_state initial_state)
: m_mutex(mx), m_locked(NO_LOCK)
{
if(initial_state == SHARED_LOCK)
rdlock();
else if(initial_state == EXCL_LOCK)
wrlock();
}
~scoped_try_rw_lock()
{
if(m_locked != NO_LOCK)
unlock();
}
void rdlock()
{
if (m_locked != NO_LOCK) throw lock_error();
rw_lock_ops<TryRWMutex>::rdlock(m_mutex);
m_locked = SHARED_LOCK;
}
bool try_rdlock()
{
if (m_locked != NO_LOCK) throw lock_error();
if(rw_lock_ops<TryRWMutex>::try_rdlock(m_mutex))
{
m_locked = SHARED_LOCK;
return true;
}
return false;
}
void wrlock()
{
if(m_locked != NO_LOCK) throw lock_error();
rw_lock_ops<TryRWMutex>::wrlock(m_mutex);
m_locked = EXCL_LOCK;
}
bool try_wrlock()
{
if (m_locked != NO_LOCK) throw lock_error();
if(rw_lock_ops<TryRWMutex>::try_wrlock(m_mutex))
{
m_locked = EXCL_LOCK;
return true;
}
return false;
}
void unlock()
{
if (m_locked == NO_LOCK) throw lock_error();
if(m_locked == SHARED_LOCK)
rw_lock_ops<TryRWMutex>::rdunlock(m_mutex);
else
rw_lock_ops<TryRWMutex>::wrunlock(m_mutex);
m_locked = NO_LOCK;
}
bool locked() const
{
return m_locked != NO_LOCK;
}
operator const void*() const
{
return (m_locked != NO_LOCK) ? this : 0;
}
rw_lock_state state() const
{
return m_locked;
}
private:
TryRWMutex& m_mutex;
rw_lock_state m_locked;
};
template <typename TimedRWMutex>
class scoped_timed_rw_lock : private noncopyable
{
public:
typedef TimedRWMutex mutex_type;
explicit scoped_timed_rw_lock(TimedRWMutex& mx, const xtime &xt)
: m_mutex(mx), m_locked(NO_LOCK)
{
timed_sharedlock(xt);
}
scoped_timed_rw_lock(TimedRWMutex& mx, rw_lock_state initial_state)
: m_mutex(mx), m_locked(NO_LOCK)
{
if(initial_state == SHARED_LOCK)
rdlock();
else if(initial_state == EXCL_LOCK)
wrlock();
}
~scoped_timed_rw_lock()
{
if(m_locked != NO_LOCK)
unlock();
}
void rdlock()
{
if (m_locked != NO_LOCK) throw lock_error();
rw_lock_ops<TimedRWMutex>::rdlock(m_mutex);
m_locked = SHARED_LOCK;
}
bool timed_rdlock(const xtime &xt)
{
if (m_locked != NO_LOCK) throw lock_error();
if(rw_lock_ops<TimedRWMutex>::timed_rdlock(m_mutex,xt))
{
m_locked = SHARED_LOCK;
return true;
}
return false;
}
void wrlock()
{
if(m_locked != NO_LOCK) throw lock_error();
rw_lock_ops<TimedRWMutex>::wrlock(m_mutex);
m_locked = EXCL_LOCK;
}
bool timed_wrlock(const xtime &xt)
{
if (m_locked != NO_LOCK) throw lock_error();
if(rw_lock_ops<TimedRWMutex>::timed_wrlock(m_mutex,xt))
{
m_locked = EXCL_LOCK;
return true;
}
return false;
}
void unlock()
{
if (m_locked == NO_LOCK) throw lock_error();
if(m_locked == SHARED_LOCK)
rw_lock_ops<TimedRWMutex>::rdunlock(m_mutex);
else
rw_lock_ops<TimedRWMutex>::wrunlock(m_mutex);
m_locked = NO_LOCK;
}
bool locked() const
{
return m_locked != NO_LOCK;
}
operator const void*() const
{
return (m_locked != NO_LOCK) ? this : 0;
}
rw_lock_state state() const
{
return m_locked;
}
private:
TimedRWMutex& m_mutex;
rw_lock_state m_locked;
};
} // namespace thread
} // namespace detail
} // namespace boost
// Change Log:
// 03/10/02 Initial version
#endif

View File

@@ -1,59 +1,64 @@
// Copyright (C) 2001-2003
// Copyright (C) 2001
// Mac Murrett
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation. Mac Murrett makes no representations
// about the suitability of this software for any purpose. It is
// provided "as is" without express or implied warranty.
//
// See http://www.boost.org for most recent version including documentation.
#ifndef BOOST_SINGLETON_MJM012402_HPP
#define BOOST_SINGLETON_MJM012402_HPP
#include <boost/thread/detail/config.hpp>
namespace boost {
namespace detail {
namespace thread {
// class singleton has the same goal as all singletons: create one instance of
// a class on demand, then dish it out as requested.
// class singleton has the same goal as all singletons: create one instance of a
// class on demand, then dish it out as requested.
template <class T>
class singleton : private T
template<class T>
class singleton: private T
{
private:
private:
singleton();
~singleton();
public:
public:
static T &instance();
};
template <class T>
template<class T>
inline singleton<T>::singleton()
{
/* no-op */
}
{ /* no-op */ }
template <class T>
template<class T>
inline singleton<T>::~singleton()
{
/* no-op */
}
{ /* no-op */ }
template <class T>
template<class T>
/*static*/ T &singleton<T>::instance()
{
// function-local static to force this to work correctly at static
// initialization time.
// function-local static to force this to work correctly at static initialization
// time.
static singleton<T> s_oT;
return(s_oT);
}
} // namespace thread
} // namespace detail
} // namespace boost
#endif // BOOST_SINGLETON_MJM012402_HPP

View File

@@ -1,532 +0,0 @@
#ifndef BOOST_THREAD_THREAD_COMMON_HPP
#define BOOST_THREAD_THREAD_COMMON_HPP
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// (C) Copyright 2007-10 Anthony Williams
#include <boost/thread/exceptions.hpp>
#ifndef BOOST_NO_IOSTREAM
#include <ostream>
#endif
#include <boost/thread/detail/move.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/xtime.hpp>
#include <boost/thread/detail/thread_heap_alloc.hpp>
#include <boost/utility.hpp>
#include <boost/assert.hpp>
#include <list>
#include <algorithm>
#include <boost/ref.hpp>
#include <boost/cstdint.hpp>
#include <boost/bind.hpp>
#include <stdlib.h>
#include <memory>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/config/abi_prefix.hpp>
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable:4251)
#endif
namespace boost
{
namespace detail
{
template<typename F>
class thread_data:
public detail::thread_data_base
{
public:
#ifndef BOOST_NO_RVALUE_REFERENCES
thread_data(F&& f_):
f(static_cast<F&&>(f_))
{}
thread_data(F& f_):
f(f_)
{}
#else
thread_data(F f_):
f(f_)
{}
thread_data(detail::thread_move_t<F> f_):
f(f_)
{}
#endif
void run()
{
f();
}
private:
F f;
void operator=(thread_data&);
thread_data(thread_data&);
};
template<typename F>
class thread_data<boost::reference_wrapper<F> >:
public detail::thread_data_base
{
private:
F& f;
void operator=(thread_data&);
thread_data(thread_data&);
public:
thread_data(boost::reference_wrapper<F> f_):
f(f_)
{}
void run()
{
f();
}
};
template<typename F>
class thread_data<const boost::reference_wrapper<F> >:
public detail::thread_data_base
{
private:
F& f;
void operator=(thread_data&);
thread_data(thread_data&);
public:
thread_data(const boost::reference_wrapper<F> f_):
f(f_)
{}
void run()
{
f();
}
};
}
class BOOST_THREAD_DECL thread
{
private:
thread(thread&);
thread& operator=(thread&);
void release_handle();
detail::thread_data_ptr thread_info;
void start_thread();
explicit thread(detail::thread_data_ptr data);
detail::thread_data_ptr get_thread_info BOOST_PREVENT_MACRO_SUBSTITUTION () const;
#ifndef BOOST_NO_RVALUE_REFERENCES
template<typename F>
static inline detail::thread_data_ptr make_thread_info(F&& f)
{
return detail::thread_data_ptr(detail::heap_new<detail::thread_data<typename boost::remove_reference<F>::type> >(static_cast<F&&>(f)));
}
static inline detail::thread_data_ptr make_thread_info(void (*f)())
{
return detail::thread_data_ptr(detail::heap_new<detail::thread_data<void(*)()> >(static_cast<void(*&&)()>(f)));
}
#else
template<typename F>
static inline detail::thread_data_ptr make_thread_info(F f)
{
return detail::thread_data_ptr(detail::heap_new<detail::thread_data<F> >(f));
}
template<typename F>
static inline detail::thread_data_ptr make_thread_info(boost::detail::thread_move_t<F> f)
{
return detail::thread_data_ptr(detail::heap_new<detail::thread_data<F> >(f));
}
#endif
struct dummy;
public:
#if BOOST_WORKAROUND(__SUNPRO_CC, < 0x5100)
thread(const volatile thread&);
#endif
thread();
~thread();
#ifndef BOOST_NO_RVALUE_REFERENCES
#ifdef BOOST_MSVC
template <class F>
explicit thread(F f,typename disable_if<boost::is_convertible<F&,detail::thread_move_t<F> >, dummy* >::type=0):
thread_info(make_thread_info(static_cast<F&&>(f)))
{
start_thread();
}
#else
template <class F>
thread(F&& f):
thread_info(make_thread_info(static_cast<F&&>(f)))
{
start_thread();
}
#endif
thread(thread&& other)
{
thread_info.swap(other.thread_info);
}
thread& operator=(thread&& other)
{
thread_info=other.thread_info;
other.thread_info.reset();
return *this;
}
thread&& move()
{
return static_cast<thread&&>(*this);
}
#else
#ifdef BOOST_NO_SFINAE
template <class F>
explicit thread(F f):
thread_info(make_thread_info(f))
{
start_thread();
}
#else
template <class F>
explicit thread(F f,typename disable_if<boost::is_convertible<F&,detail::thread_move_t<F> >, dummy* >::type=0):
thread_info(make_thread_info(f))
{
start_thread();
}
#endif
template <class F>
explicit thread(detail::thread_move_t<F> f):
thread_info(make_thread_info(f))
{
start_thread();
}
thread(detail::thread_move_t<thread> x)
{
thread_info=x->thread_info;
x->thread_info.reset();
}
#if BOOST_WORKAROUND(__SUNPRO_CC, < 0x5100)
thread& operator=(thread x)
{
swap(x);
return *this;
}
#else
thread& operator=(detail::thread_move_t<thread> x)
{
thread new_thread(x);
swap(new_thread);
return *this;
}
#endif
operator detail::thread_move_t<thread>()
{
return move();
}
detail::thread_move_t<thread> move()
{
detail::thread_move_t<thread> x(*this);
return x;
}
#endif
template <class F,class A1>
thread(F f,A1 a1):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1)))
{
start_thread();
}
template <class F,class A1,class A2>
thread(F f,A1 a1,A2 a2):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2)))
{
start_thread();
}
template <class F,class A1,class A2,class A3>
thread(F f,A1 a1,A2 a2,A3 a3):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2,a3)))
{
start_thread();
}
template <class F,class A1,class A2,class A3,class A4>
thread(F f,A1 a1,A2 a2,A3 a3,A4 a4):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2,a3,a4)))
{
start_thread();
}
template <class F,class A1,class A2,class A3,class A4,class A5>
thread(F f,A1 a1,A2 a2,A3 a3,A4 a4,A5 a5):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2,a3,a4,a5)))
{
start_thread();
}
template <class F,class A1,class A2,class A3,class A4,class A5,class A6>
thread(F f,A1 a1,A2 a2,A3 a3,A4 a4,A5 a5,A6 a6):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2,a3,a4,a5,a6)))
{
start_thread();
}
template <class F,class A1,class A2,class A3,class A4,class A5,class A6,class A7>
thread(F f,A1 a1,A2 a2,A3 a3,A4 a4,A5 a5,A6 a6,A7 a7):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2,a3,a4,a5,a6,a7)))
{
start_thread();
}
template <class F,class A1,class A2,class A3,class A4,class A5,class A6,class A7,class A8>
thread(F f,A1 a1,A2 a2,A3 a3,A4 a4,A5 a5,A6 a6,A7 a7,A8 a8):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2,a3,a4,a5,a6,a7,a8)))
{
start_thread();
}
template <class F,class A1,class A2,class A3,class A4,class A5,class A6,class A7,class A8,class A9>
thread(F f,A1 a1,A2 a2,A3 a3,A4 a4,A5 a5,A6 a6,A7 a7,A8 a8,A9 a9):
thread_info(make_thread_info(boost::bind(boost::type<void>(),f,a1,a2,a3,a4,a5,a6,a7,a8,a9)))
{
start_thread();
}
void swap(thread& x)
{
thread_info.swap(x.thread_info);
}
class id;
id get_id() const;
bool joinable() const;
void join();
bool timed_join(const system_time& wait_until);
template<typename TimeDuration>
inline bool timed_join(TimeDuration const& rel_time)
{
return timed_join(get_system_time()+rel_time);
}
void detach();
static unsigned hardware_concurrency();
typedef detail::thread_data_base::native_handle_type native_handle_type;
native_handle_type native_handle();
// backwards compatibility
bool operator==(const thread& other) const;
bool operator!=(const thread& other) const;
static inline void yield()
{
this_thread::yield();
}
static inline void sleep(const system_time& xt)
{
this_thread::sleep(xt);
}
// extensions
void interrupt();
bool interruption_requested() const;
};
inline void swap(thread& lhs,thread& rhs)
{
return lhs.swap(rhs);
}
#ifndef BOOST_NO_RVALUE_REFERENCES
inline thread&& move(thread& t)
{
return static_cast<thread&&>(t);
}
inline thread&& move(thread&& t)
{
return static_cast<thread&&>(t);
}
#else
inline detail::thread_move_t<thread> move(detail::thread_move_t<thread> t)
{
return t;
}
#endif
namespace this_thread
{
thread::id BOOST_THREAD_DECL get_id();
void BOOST_THREAD_DECL interruption_point();
bool BOOST_THREAD_DECL interruption_enabled();
bool BOOST_THREAD_DECL interruption_requested();
inline void sleep(xtime const& abs_time)
{
sleep(system_time(abs_time));
}
}
class thread::id
{
private:
detail::thread_data_ptr thread_data;
id(detail::thread_data_ptr thread_data_):
thread_data(thread_data_)
{}
friend class thread;
friend id BOOST_THREAD_DECL this_thread::get_id();
public:
id():
thread_data()
{}
bool operator==(const id& y) const
{
return thread_data==y.thread_data;
}
bool operator!=(const id& y) const
{
return thread_data!=y.thread_data;
}
bool operator<(const id& y) const
{
return thread_data<y.thread_data;
}
bool operator>(const id& y) const
{
return y.thread_data<thread_data;
}
bool operator<=(const id& y) const
{
return !(y.thread_data<thread_data);
}
bool operator>=(const id& y) const
{
return !(thread_data<y.thread_data);
}
#ifndef BOOST_NO_IOSTREAM
#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
template<class charT, class traits>
friend std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const id& x)
{
if(x.thread_data)
{
return os<<x.thread_data;
}
else
{
return os<<"{Not-any-thread}";
}
}
#else
template<class charT, class traits>
std::basic_ostream<charT, traits>&
print(std::basic_ostream<charT, traits>& os) const
{
if(thread_data)
{
return os<<thread_data;
}
else
{
return os<<"{Not-any-thread}";
}
}
#endif
#endif
};
#if !defined(BOOST_NO_IOSTREAM) && defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)
template<class charT, class traits>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const thread::id& x)
{
return x.print(os);
}
#endif
inline bool thread::operator==(const thread& other) const
{
return get_id()==other.get_id();
}
inline bool thread::operator!=(const thread& other) const
{
return get_id()!=other.get_id();
}
namespace detail
{
struct thread_exit_function_base
{
virtual ~thread_exit_function_base()
{}
virtual void operator()()=0;
};
template<typename F>
struct thread_exit_function:
thread_exit_function_base
{
F f;
thread_exit_function(F f_):
f(f_)
{}
void operator()()
{
f();
}
};
void BOOST_THREAD_DECL add_thread_exit_function(thread_exit_function_base*);
}
namespace this_thread
{
template<typename F>
void at_thread_exit(F f)
{
detail::thread_exit_function_base* const thread_exit_func=detail::heap_new<detail::thread_exit_function<F> >(f);
detail::add_thread_exit_function(thread_exit_func);
}
}
}
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
#include <boost/config/abi_suffix.hpp>
#endif

View File

@@ -1,108 +0,0 @@
#ifndef BOOST_THREAD_DETAIL_THREAD_GROUP_HPP
#define BOOST_THREAD_DETAIL_THREAD_GROUP_HPP
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// (C) Copyright 2007-9 Anthony Williams
#include <list>
#include <boost/thread/shared_mutex.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/config/abi_prefix.hpp>
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable:4251)
#endif
namespace boost
{
class thread_group
{
private:
thread_group(thread_group const&);
thread_group& operator=(thread_group const&);
public:
thread_group() {}
~thread_group()
{
for(std::list<thread*>::iterator it=threads.begin(),end=threads.end();
it!=end;
++it)
{
delete *it;
}
}
template<typename F>
thread* create_thread(F threadfunc)
{
boost::lock_guard<shared_mutex> guard(m);
std::auto_ptr<thread> new_thread(new thread(threadfunc));
threads.push_back(new_thread.get());
return new_thread.release();
}
void add_thread(thread* thrd)
{
if(thrd)
{
boost::lock_guard<shared_mutex> guard(m);
threads.push_back(thrd);
}
}
void remove_thread(thread* thrd)
{
boost::lock_guard<shared_mutex> guard(m);
std::list<thread*>::iterator const it=std::find(threads.begin(),threads.end(),thrd);
if(it!=threads.end())
{
threads.erase(it);
}
}
void join_all()
{
boost::shared_lock<shared_mutex> guard(m);
for(std::list<thread*>::iterator it=threads.begin(),end=threads.end();
it!=end;
++it)
{
(*it)->join();
}
}
void interrupt_all()
{
boost::shared_lock<shared_mutex> guard(m);
for(std::list<thread*>::iterator it=threads.begin(),end=threads.end();
it!=end;
++it)
{
(*it)->interrupt();
}
}
size_t size() const
{
boost::shared_lock<shared_mutex> guard(m);
return threads.size();
}
private:
std::list<thread*> threads;
mutable shared_mutex m;
};
}
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
#include <boost/config/abi_suffix.hpp>
#endif

View File

@@ -1,23 +0,0 @@
#ifndef BOOST_THREAD_THREAD_HEAP_ALLOC_HPP
#define BOOST_THREAD_THREAD_HEAP_ALLOC_HPP
// thread_heap_alloc.hpp
//
// (C) Copyright 2008 Anthony Williams
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/thread/detail/platform.hpp>
#if defined(BOOST_THREAD_PLATFORM_WIN32)
#include <boost/thread/win32/thread_heap_alloc.hpp>
#elif defined(BOOST_THREAD_PLATFORM_PTHREAD)
#include <boost/thread/pthread/thread_heap_alloc.hpp>
#else
#error "Boost threads unavailable on this platform"
#endif
#endif

View File

@@ -1,35 +0,0 @@
#ifndef BOOST_THREAD_DETAIL_THREAD_INTERRUPTION_HPP
#define BOOST_THREAD_DETAIL_THREAD_INTERRUPTION_HPP
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// (C) Copyright 2007-9 Anthony Williams
namespace boost
{
namespace this_thread
{
class BOOST_THREAD_DECL disable_interruption
{
disable_interruption(const disable_interruption&);
disable_interruption& operator=(const disable_interruption&);
bool interruption_was_enabled;
friend class restore_interruption;
public:
disable_interruption();
~disable_interruption();
};
class BOOST_THREAD_DECL restore_interruption
{
restore_interruption(const restore_interruption&);
restore_interruption& operator=(const restore_interruption&);
public:
explicit restore_interruption(disable_interruption& d);
~restore_interruption();
};
}
}
#endif

View File

@@ -1,65 +0,0 @@
// (C) Copyright Michael Glassford 2004.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(BOOST_TLS_HOOKS_HPP)
#define BOOST_TLS_HOOKS_HPP
#include <boost/thread/detail/config.hpp>
#include <boost/config/abi_prefix.hpp>
#if defined(BOOST_HAS_WINTHREADS)
namespace boost
{
BOOST_THREAD_DECL void __cdecl on_process_enter(void);
//Function to be called when the exe or dll
//that uses Boost.Threads first starts
//or is first loaded.
//Should be called only before the first call to
//on_thread_enter().
//Called automatically by Boost.Threads when
//a method for doing so has been discovered.
//May be omitted; may be called multiple times.
BOOST_THREAD_DECL void __cdecl on_process_exit(void);
//Function to be called when the exe or dll
//that uses Boost.Threads first starts
//or is first loaded.
//Should be called only after the last call to
//on_exit_thread().
//Called automatically by Boost.Threads when
//a method for doing so has been discovered.
//Must not be omitted; may be called multiple times.
BOOST_THREAD_DECL void __cdecl on_thread_enter(void);
//Function to be called just after a thread starts
//in an exe or dll that uses Boost.Threads.
//Must be called in the context of the thread
//that is starting.
//Called automatically by Boost.Threads when
//a method for doing so has been discovered.
//May be omitted; may be called multiple times.
BOOST_THREAD_DECL void __cdecl on_thread_exit(void);
//Function to be called just be fore a thread ends
//in an exe or dll that uses Boost.Threads.
//Must be called in the context of the thread
//that is ending.
//Called automatically by Boost.Threads when
//a method for doing so has been discovered.
//Must not be omitted; may be called multiple times.
void tss_cleanup_implemented();
//Dummy function used both to detect whether tss cleanup
//cleanup has been implemented and to force
//it to be linked into the Boost.Threads library.
}
#endif //defined(BOOST_HAS_WINTHREADS)
#include <boost/config/abi_suffix.hpp>
#endif //!defined(BOOST_TLS_HOOKS_HPP)

View File

@@ -1,182 +1,39 @@
// Copyright (C) 2001-2003
// Copyright (C) 2001
// William E. Kempf
// Copyright (C) 2007-9 Anthony Williams
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation. William E. Kempf makes no representations
// about the suitability of this software for any purpose.
// It is provided "as is" without express or implied warranty.
#ifndef BOOST_THREAD_EXCEPTIONS_PDM070801_H
#define BOOST_THREAD_EXCEPTIONS_PDM070801_H
#include <boost/thread/detail/config.hpp>
// pdm: Sorry, but this class is used all over the place & I end up
// with recursive headers if I don't separate it
// wek: Not sure why recursive headers would cause compilation problems
// given the include guards, but regardless it makes sense to
// seperate this out any way.
#include <string>
#include <stdexcept>
#include <boost/config/abi_prefix.hpp>
namespace boost {
namespace boost
class lock_error : public std::logic_error
{
public:
lock_error();
};
class thread_interrupted
{};
class thread_exception:
public std::exception
{
protected:
thread_exception():
m_sys_err(0)
{}
thread_exception(int sys_err_code):
m_sys_err(sys_err_code)
{}
public:
~thread_exception() throw()
{}
int native_error() const
{
return m_sys_err;
}
private:
int m_sys_err;
};
class condition_error:
public std::exception
{
public:
const char* what() const throw()
{
return "Condition error";
}
};
class lock_error:
public thread_exception
{
public:
lock_error()
{}
lock_error(int sys_err_code):
thread_exception(sys_err_code)
{}
~lock_error() throw()
{}
virtual const char* what() const throw()
{
return "boost::lock_error";
}
};
class thread_resource_error:
public thread_exception
{
public:
thread_resource_error()
{}
thread_resource_error(int sys_err_code):
thread_exception(sys_err_code)
{}
~thread_resource_error() throw()
{}
virtual const char* what() const throw()
{
return "boost::thread_resource_error";
}
};
class unsupported_thread_option:
public thread_exception
{
public:
unsupported_thread_option()
{}
unsupported_thread_option(int sys_err_code):
thread_exception(sys_err_code)
{}
~unsupported_thread_option() throw()
{}
virtual const char* what() const throw()
{
return "boost::unsupported_thread_option";
}
};
class invalid_thread_argument:
public thread_exception
{
public:
invalid_thread_argument()
{}
invalid_thread_argument(int sys_err_code):
thread_exception(sys_err_code)
{}
~invalid_thread_argument() throw()
{}
virtual const char* what() const throw()
{
return "boost::invalid_thread_argument";
}
};
class thread_permission_error:
public thread_exception
{
public:
thread_permission_error()
{}
thread_permission_error(int sys_err_code):
thread_exception(sys_err_code)
{}
~thread_permission_error() throw()
{}
virtual const char* what() const throw()
{
return "boost::thread_permission_error";
}
};
class thread_resource_error : public std::runtime_error
{
public:
thread_resource_error();
};
} // namespace boost
#include <boost/config/abi_suffix.hpp>
#endif
#endif // BOOST_THREAD_CONFIG_PDM070801_H

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,21 +1,164 @@
#ifndef BOOST_THREAD_MUTEX_HPP
#define BOOST_THREAD_MUTEX_HPP
// mutex.hpp
// Copyright (C) 2001
// William E. Kempf
//
// (C) Copyright 2007 Anthony Williams
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation. William E. Kempf makes no representations
// about the suitability of this software for any purpose.
// It is provided "as is" without express or implied warranty.
#include <boost/thread/detail/platform.hpp>
#if defined(BOOST_THREAD_PLATFORM_WIN32)
#include <boost/thread/win32/mutex.hpp>
#elif defined(BOOST_THREAD_PLATFORM_PTHREAD)
#include <boost/thread/pthread/mutex.hpp>
#else
#error "Boost threads unavailable on this platform"
#ifndef BOOST_MUTEX_WEK070601_HPP
#define BOOST_MUTEX_WEK070601_HPP
#include <boost/config.hpp>
#ifndef BOOST_HAS_THREADS
# error Thread support is unavailable!
#endif
#include <boost/utility.hpp>
#include <boost/thread/detail/lock.hpp>
#if defined(BOOST_HAS_PTHREADS)
# include <pthread.h>
#endif
#if defined(BOOST_HAS_MPTASKS)
# include "scoped_critical_region.hpp"
#endif
namespace boost {
struct xtime;
class mutex : private noncopyable
{
public:
friend class detail::thread::lock_ops<mutex>;
typedef detail::thread::scoped_lock<mutex> scoped_lock;
mutex();
~mutex();
private:
#if defined(BOOST_HAS_WINTHREADS)
typedef void* cv_state;
#elif defined(BOOST_HAS_PTHREADS)
struct cv_state
{
pthread_mutex_t* pmutex;
};
#elif defined(BOOST_HAS_MPTASKS)
struct cv_state
{
};
#endif
void do_lock();
void do_unlock();
void do_lock(cv_state& state);
void do_unlock(cv_state& state);
#if defined(BOOST_HAS_WINTHREADS)
void* m_mutex;
#elif defined(BOOST_HAS_PTHREADS)
pthread_mutex_t m_mutex;
#elif defined(BOOST_HAS_MPTASKS)
threads::mac::detail::scoped_critical_region m_mutex;
threads::mac::detail::scoped_critical_region m_mutex_mutex;
#endif
};
class try_mutex : private noncopyable
{
public:
friend class detail::thread::lock_ops<try_mutex>;
typedef detail::thread::scoped_lock<try_mutex> scoped_lock;
typedef detail::thread::scoped_try_lock<try_mutex> scoped_try_lock;
try_mutex();
~try_mutex();
private:
#if defined(BOOST_HAS_WINTHREADS)
typedef void* cv_state;
#elif defined(BOOST_HAS_PTHREADS)
struct cv_state
{
pthread_mutex_t* pmutex;
};
#elif defined(BOOST_HAS_MPTASKS)
struct cv_state
{
};
#endif
void do_lock();
bool do_trylock();
void do_unlock();
void do_lock(cv_state& state);
void do_unlock(cv_state& state);
#if defined(BOOST_HAS_WINTHREADS)
void* m_mutex;
#elif defined(BOOST_HAS_PTHREADS)
pthread_mutex_t m_mutex;
#elif defined(BOOST_HAS_MPTASKS)
threads::mac::detail::scoped_critical_region m_mutex;
threads::mac::detail::scoped_critical_region m_mutex_mutex;
#endif
};
class timed_mutex : private noncopyable
{
public:
friend class detail::thread::lock_ops<timed_mutex>;
typedef detail::thread::scoped_lock<timed_mutex> scoped_lock;
typedef detail::thread::scoped_try_lock<timed_mutex> scoped_try_lock;
typedef detail::thread::scoped_timed_lock<timed_mutex> scoped_timed_lock;
timed_mutex();
~timed_mutex();
private:
#if defined(BOOST_HAS_WINTHREADS)
typedef void* cv_state;
#elif defined(BOOST_HAS_PTHREADS)
struct cv_state
{
pthread_mutex_t* pmutex;
};
#elif defined(BOOST_HAS_MPTASKS)
struct cv_state
{
};
#endif
void do_lock();
bool do_trylock();
bool do_timedlock(const xtime& xt);
void do_unlock();
void do_lock(cv_state& state);
void do_unlock(cv_state& state);
#if defined(BOOST_HAS_WINTHREADS)
void* m_mutex;
#elif defined(BOOST_HAS_PTHREADS)
pthread_mutex_t m_mutex;
pthread_cond_t m_condition;
bool m_locked;
#elif defined(BOOST_HAS_MPTASKS)
threads::mac::detail::scoped_critical_region m_mutex;
threads::mac::detail::scoped_critical_region m_mutex_mutex;
#endif
};
} // namespace boost
// Change Log:
// 8 Feb 01 WEKEMPF Initial version.
// 22 May 01 WEKEMPF Modified to use xtime for time outs. Factored out
// to three classes, mutex, try_mutex and timed_mutex.
#endif // BOOST_MUTEX_WEK070601_HPP

View File

@@ -1,33 +1,45 @@
#ifndef BOOST_THREAD_ONCE_HPP
#define BOOST_THREAD_ONCE_HPP
// once.hpp
// Copyright (C) 2001
// William E. Kempf
//
// (C) Copyright 2006-7 Anthony Williams
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation. William E. Kempf makes no representations
// about the suitability of this software for any purpose.
// It is provided "as is" without express or implied warranty.
#include <boost/thread/detail/platform.hpp>
#if defined(BOOST_THREAD_PLATFORM_WIN32)
#include <boost/thread/win32/once.hpp>
#elif defined(BOOST_THREAD_PLATFORM_PTHREAD)
#include <boost/thread/pthread/once.hpp>
#else
#error "Boost threads unavailable on this platform"
#ifndef BOOST_ONCE_WEK080101_HPP
#define BOOST_ONCE_WEK080101_HPP
#include <boost/config.hpp>
#ifndef BOOST_HAS_THREADS
# error Thread support is unavailable!
#endif
#include <boost/config/abi_prefix.hpp>
#if defined(BOOST_HAS_PTHREADS)
# include <pthread.h>
#endif
namespace boost
{
inline void call_once(void (*func)(),once_flag& flag)
{
call_once(flag,func);
}
}
namespace boost {
#include <boost/config/abi_suffix.hpp>
#if defined(BOOST_HAS_PTHREADS)
typedef pthread_once_t once_flag;
#define BOOST_ONCE_INIT PTHREAD_ONCE_INIT
#elif (defined(BOOST_HAS_WINTHREADS) || defined(BOOST_HAS_MPTASKS))
typedef long once_flag;
#define BOOST_ONCE_INIT 0
#endif
void call_once(void (*func)(), once_flag& flag);
} // namespace boost
// Change Log:
// 1 Aug 01 WEKEMPF Initial version.
#endif // BOOST_ONCE_WEK080101_HPP

View File

@@ -1,212 +0,0 @@
#ifndef BOOST_THREAD_CONDITION_VARIABLE_PTHREAD_HPP
#define BOOST_THREAD_CONDITION_VARIABLE_PTHREAD_HPP
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// (C) Copyright 2007-10 Anthony Williams
#include "timespec.hpp"
#include "pthread_mutex_scoped_lock.hpp"
#include "thread_data.hpp"
#include "condition_variable_fwd.hpp"
#include <boost/config/abi_prefix.hpp>
namespace boost
{
namespace this_thread
{
void BOOST_THREAD_DECL interruption_point();
}
namespace thread_cv_detail
{
template<typename MutexType>
struct lock_on_exit
{
MutexType* m;
lock_on_exit():
m(0)
{}
void activate(MutexType& m_)
{
m_.unlock();
m=&m_;
}
~lock_on_exit()
{
if(m)
{
m->lock();
}
}
};
}
inline void condition_variable::wait(unique_lock<mutex>& m)
{
thread_cv_detail::lock_on_exit<unique_lock<mutex> > guard;
detail::interruption_checker check_for_interruption(&internal_mutex,&cond);
guard.activate(m);
int const res=pthread_cond_wait(&cond,&internal_mutex);
BOOST_ASSERT(!res);
this_thread::interruption_point();
}
inline bool condition_variable::timed_wait(unique_lock<mutex>& m,boost::system_time const& wait_until)
{
thread_cv_detail::lock_on_exit<unique_lock<mutex> > guard;
detail::interruption_checker check_for_interruption(&internal_mutex,&cond);
guard.activate(m);
struct timespec const timeout=detail::get_timespec(wait_until);
int const cond_res=pthread_cond_timedwait(&cond,&internal_mutex,&timeout);
this_thread::interruption_point();
if(cond_res==ETIMEDOUT)
{
return false;
}
BOOST_ASSERT(!cond_res);
return true;
}
inline void condition_variable::notify_one()
{
boost::pthread::pthread_mutex_scoped_lock internal_lock(&internal_mutex);
BOOST_VERIFY(!pthread_cond_signal(&cond));
}
inline void condition_variable::notify_all()
{
boost::pthread::pthread_mutex_scoped_lock internal_lock(&internal_mutex);
BOOST_VERIFY(!pthread_cond_broadcast(&cond));
}
class condition_variable_any
{
pthread_mutex_t internal_mutex;
pthread_cond_t cond;
condition_variable_any(condition_variable_any&);
condition_variable_any& operator=(condition_variable_any&);
public:
condition_variable_any()
{
int const res=pthread_mutex_init(&internal_mutex,NULL);
if(res)
{
boost::throw_exception(thread_resource_error());
}
int const res2=pthread_cond_init(&cond,NULL);
if(res2)
{
BOOST_VERIFY(!pthread_mutex_destroy(&internal_mutex));
boost::throw_exception(thread_resource_error());
}
}
~condition_variable_any()
{
BOOST_VERIFY(!pthread_mutex_destroy(&internal_mutex));
BOOST_VERIFY(!pthread_cond_destroy(&cond));
}
template<typename lock_type>
void wait(lock_type& m)
{
int res=0;
{
thread_cv_detail::lock_on_exit<lock_type> guard;
detail::interruption_checker check_for_interruption(&internal_mutex,&cond);
guard.activate(m);
res=pthread_cond_wait(&cond,&internal_mutex);
this_thread::interruption_point();
}
if(res)
{
boost::throw_exception(condition_error());
}
}
template<typename lock_type,typename predicate_type>
void wait(lock_type& m,predicate_type pred)
{
while(!pred()) wait(m);
}
template<typename lock_type>
bool timed_wait(lock_type& m,boost::system_time const& wait_until)
{
struct timespec const timeout=detail::get_timespec(wait_until);
int res=0;
{
thread_cv_detail::lock_on_exit<lock_type> guard;
detail::interruption_checker check_for_interruption(&internal_mutex,&cond);
guard.activate(m);
res=pthread_cond_timedwait(&cond,&internal_mutex,&timeout);
this_thread::interruption_point();
}
if(res==ETIMEDOUT)
{
return false;
}
if(res)
{
boost::throw_exception(condition_error());
}
return true;
}
template<typename lock_type>
bool timed_wait(lock_type& m,xtime const& wait_until)
{
return timed_wait(m,system_time(wait_until));
}
template<typename lock_type,typename duration_type>
bool timed_wait(lock_type& m,duration_type const& wait_duration)
{
return timed_wait(m,get_system_time()+wait_duration);
}
template<typename lock_type,typename predicate_type>
bool timed_wait(lock_type& m,boost::system_time const& wait_until,predicate_type pred)
{
while (!pred())
{
if(!timed_wait(m, wait_until))
return pred();
}
return true;
}
template<typename lock_type,typename predicate_type>
bool timed_wait(lock_type& m,xtime const& wait_until,predicate_type pred)
{
return timed_wait(m,system_time(wait_until),pred);
}
template<typename lock_type,typename duration_type,typename predicate_type>
bool timed_wait(lock_type& m,duration_type const& wait_duration,predicate_type pred)
{
return timed_wait(m,get_system_time()+wait_duration,pred);
}
void notify_one()
{
boost::pthread::pthread_mutex_scoped_lock internal_lock(&internal_mutex);
BOOST_VERIFY(!pthread_cond_signal(&cond));
}
void notify_all()
{
boost::pthread::pthread_mutex_scoped_lock internal_lock(&internal_mutex);
BOOST_VERIFY(!pthread_cond_broadcast(&cond));
}
};
}
#include <boost/config/abi_suffix.hpp>
#endif

View File

@@ -1,107 +0,0 @@
#ifndef BOOST_THREAD_PTHREAD_CONDITION_VARIABLE_FWD_HPP
#define BOOST_THREAD_PTHREAD_CONDITION_VARIABLE_FWD_HPP
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// (C) Copyright 2007-8 Anthony Williams
#include <boost/assert.hpp>
#include <boost/throw_exception.hpp>
#include <pthread.h>
#include <boost/thread/mutex.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/thread_time.hpp>
#include <boost/thread/xtime.hpp>
#include <boost/config/abi_prefix.hpp>
namespace boost
{
class condition_variable
{
private:
pthread_mutex_t internal_mutex;
pthread_cond_t cond;
condition_variable(condition_variable&);
condition_variable& operator=(condition_variable&);
public:
condition_variable()
{
int const res=pthread_mutex_init(&internal_mutex,NULL);
if(res)
{
boost::throw_exception(thread_resource_error());
}
int const res2=pthread_cond_init(&cond,NULL);
if(res2)
{
BOOST_VERIFY(!pthread_mutex_destroy(&internal_mutex));
boost::throw_exception(thread_resource_error());
}
}
~condition_variable()
{
BOOST_VERIFY(!pthread_mutex_destroy(&internal_mutex));
BOOST_VERIFY(!pthread_cond_destroy(&cond));
}
void wait(unique_lock<mutex>& m);
template<typename predicate_type>
void wait(unique_lock<mutex>& m,predicate_type pred)
{
while(!pred()) wait(m);
}
inline bool timed_wait(unique_lock<mutex>& m,
boost::system_time const& wait_until);
bool timed_wait(unique_lock<mutex>& m,xtime const& wait_until)
{
return timed_wait(m,system_time(wait_until));
}
template<typename duration_type>
bool timed_wait(unique_lock<mutex>& m,duration_type const& wait_duration)
{
return timed_wait(m,get_system_time()+wait_duration);
}
template<typename predicate_type>
bool timed_wait(unique_lock<mutex>& m,boost::system_time const& wait_until,predicate_type pred)
{
while (!pred())
{
if(!timed_wait(m, wait_until))
return pred();
}
return true;
}
template<typename predicate_type>
bool timed_wait(unique_lock<mutex>& m,xtime const& wait_until,predicate_type pred)
{
return timed_wait(m,system_time(wait_until),pred);
}
template<typename duration_type,typename predicate_type>
bool timed_wait(unique_lock<mutex>& m,duration_type const& wait_duration,predicate_type pred)
{
return timed_wait(m,get_system_time()+wait_duration,pred);
}
typedef pthread_cond_t* native_handle_type;
native_handle_type native_handle()
{
return &cond;
}
void notify_one();
void notify_all();
};
}
#include <boost/config/abi_suffix.hpp>
#endif

View File

@@ -1,222 +0,0 @@
#ifndef BOOST_THREAD_PTHREAD_MUTEX_HPP
#define BOOST_THREAD_PTHREAD_MUTEX_HPP
// (C) Copyright 2007-8 Anthony Williams
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <pthread.h>
#include <boost/utility.hpp>
#include <boost/throw_exception.hpp>
#include <boost/thread/exceptions.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/thread_time.hpp>
#include <boost/thread/xtime.hpp>
#include <boost/assert.hpp>
#include <errno.h>
#include "timespec.hpp"
#include "pthread_mutex_scoped_lock.hpp"
#ifdef _POSIX_TIMEOUTS
#if _POSIX_TIMEOUTS >= 0
#define BOOST_PTHREAD_HAS_TIMEDLOCK
#endif
#endif
#include <boost/config/abi_prefix.hpp>
namespace boost
{
class mutex
{
private:
mutex(mutex const&);
mutex& operator=(mutex const&);
pthread_mutex_t m;
public:
mutex()
{
int const res=pthread_mutex_init(&m,NULL);
if(res)
{
boost::throw_exception(thread_resource_error());
}
}
~mutex()
{
BOOST_VERIFY(!pthread_mutex_destroy(&m));
}
void lock()
{
int const res=pthread_mutex_lock(&m);
if(res)
{
boost::throw_exception(lock_error(res));
}
}
void unlock()
{
BOOST_VERIFY(!pthread_mutex_unlock(&m));
}
bool try_lock()
{
int const res=pthread_mutex_trylock(&m);
if(res && (res!=EBUSY))
{
boost::throw_exception(lock_error(res));
}
return !res;
}
typedef pthread_mutex_t* native_handle_type;
native_handle_type native_handle()
{
return &m;
}
typedef unique_lock<mutex> scoped_lock;
typedef detail::try_lock_wrapper<mutex> scoped_try_lock;
};
typedef mutex try_mutex;
class timed_mutex
{
private:
timed_mutex(timed_mutex const&);
timed_mutex& operator=(timed_mutex const&);
private:
pthread_mutex_t m;
#ifndef BOOST_PTHREAD_HAS_TIMEDLOCK
pthread_cond_t cond;
bool is_locked;
#endif
public:
timed_mutex()
{
int const res=pthread_mutex_init(&m,NULL);
if(res)
{
boost::throw_exception(thread_resource_error());
}
#ifndef BOOST_PTHREAD_HAS_TIMEDLOCK
int const res2=pthread_cond_init(&cond,NULL);
if(res2)
{
BOOST_VERIFY(!pthread_mutex_destroy(&m));
boost::throw_exception(thread_resource_error());
}
is_locked=false;
#endif
}
~timed_mutex()
{
BOOST_VERIFY(!pthread_mutex_destroy(&m));
#ifndef BOOST_PTHREAD_HAS_TIMEDLOCK
BOOST_VERIFY(!pthread_cond_destroy(&cond));
#endif
}
template<typename TimeDuration>
bool timed_lock(TimeDuration const & relative_time)
{
return timed_lock(get_system_time()+relative_time);
}
bool timed_lock(boost::xtime const & absolute_time)
{
return timed_lock(system_time(absolute_time));
}
#ifdef BOOST_PTHREAD_HAS_TIMEDLOCK
void lock()
{
BOOST_VERIFY(!pthread_mutex_lock(&m));
}
void unlock()
{
BOOST_VERIFY(!pthread_mutex_unlock(&m));
}
bool try_lock()
{
int const res=pthread_mutex_trylock(&m);
BOOST_ASSERT(!res || res==EBUSY);
return !res;
}
bool timed_lock(system_time const & abs_time)
{
struct timespec const timeout=detail::get_timespec(abs_time);
int const res=pthread_mutex_timedlock(&m,&timeout);
BOOST_ASSERT(!res || res==ETIMEDOUT);
return !res;
}
typedef pthread_mutex_t* native_handle_type;
native_handle_type native_handle()
{
return &m;
}
#else
void lock()
{
boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
while(is_locked)
{
BOOST_VERIFY(!pthread_cond_wait(&cond,&m));
}
is_locked=true;
}
void unlock()
{
boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
is_locked=false;
BOOST_VERIFY(!pthread_cond_signal(&cond));
}
bool try_lock()
{
boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
if(is_locked)
{
return false;
}
is_locked=true;
return true;
}
bool timed_lock(system_time const & abs_time)
{
struct timespec const timeout=detail::get_timespec(abs_time);
boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
while(is_locked)
{
int const cond_res=pthread_cond_timedwait(&cond,&m,&timeout);
if(cond_res==ETIMEDOUT)
{
return false;
}
BOOST_ASSERT(!cond_res);
}
is_locked=true;
return true;
}
#endif
typedef unique_lock<timed_mutex> scoped_timed_lock;
typedef detail::try_lock_wrapper<timed_mutex> scoped_try_lock;
typedef scoped_timed_lock scoped_lock;
};
}
#include <boost/config/abi_suffix.hpp>
#endif

View File

@@ -1,95 +0,0 @@
#ifndef BOOST_THREAD_PTHREAD_ONCE_HPP
#define BOOST_THREAD_PTHREAD_ONCE_HPP
// once.hpp
//
// (C) Copyright 2007-8 Anthony Williams
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/thread/detail/config.hpp>
#include <boost/config.hpp>
#include <pthread.h>
#include <boost/assert.hpp>
#include "pthread_mutex_scoped_lock.hpp"
#include <boost/thread/pthread/pthread_mutex_scoped_lock.hpp>
#include <boost/cstdint.hpp>
#include <boost/config/abi_prefix.hpp>
namespace boost
{
struct once_flag
{
boost::uintmax_t epoch;
};
namespace detail
{
BOOST_THREAD_DECL boost::uintmax_t& get_once_per_thread_epoch();
BOOST_THREAD_DECL extern boost::uintmax_t once_global_epoch;
BOOST_THREAD_DECL extern pthread_mutex_t once_epoch_mutex;
BOOST_THREAD_DECL extern pthread_cond_t once_epoch_cv;
}
#define BOOST_ONCE_INITIAL_FLAG_VALUE 0
#define BOOST_ONCE_INIT {BOOST_ONCE_INITIAL_FLAG_VALUE}
// Based on Mike Burrows fast_pthread_once algorithm as described in
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2444.html
template<typename Function>
void call_once(once_flag& flag,Function f)
{
static boost::uintmax_t const uninitialized_flag=BOOST_ONCE_INITIAL_FLAG_VALUE;
static boost::uintmax_t const being_initialized=uninitialized_flag+1;
boost::uintmax_t const epoch=flag.epoch;
boost::uintmax_t& this_thread_epoch=detail::get_once_per_thread_epoch();
if(epoch<this_thread_epoch)
{
pthread::pthread_mutex_scoped_lock lk(&detail::once_epoch_mutex);
while(flag.epoch<=being_initialized)
{
if(flag.epoch==uninitialized_flag)
{
flag.epoch=being_initialized;
#ifndef BOOST_NO_EXCEPTIONS
try
{
#endif
pthread::pthread_mutex_scoped_unlock relocker(&detail::once_epoch_mutex);
f();
#ifndef BOOST_NO_EXCEPTIONS
}
catch(...)
{
flag.epoch=uninitialized_flag;
BOOST_VERIFY(!pthread_cond_broadcast(&detail::once_epoch_cv));
throw;
}
#endif
flag.epoch=--detail::once_global_epoch;
BOOST_VERIFY(!pthread_cond_broadcast(&detail::once_epoch_cv));
}
else
{
while(flag.epoch==being_initialized)
{
BOOST_VERIFY(!pthread_cond_wait(&detail::once_epoch_cv,&detail::once_epoch_mutex));
}
}
}
this_thread_epoch=detail::once_global_epoch;
}
}
}
#include <boost/config/abi_suffix.hpp>
#endif

View File

@@ -1,64 +0,0 @@
#ifndef BOOST_PTHREAD_MUTEX_SCOPED_LOCK_HPP
#define BOOST_PTHREAD_MUTEX_SCOPED_LOCK_HPP
// (C) Copyright 2007-8 Anthony Williams
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <pthread.h>
#include <boost/assert.hpp>
#include <boost/config/abi_prefix.hpp>
namespace boost
{
namespace pthread
{
class pthread_mutex_scoped_lock
{
pthread_mutex_t* m;
bool locked;
public:
explicit pthread_mutex_scoped_lock(pthread_mutex_t* m_):
m(m_),locked(true)
{
BOOST_VERIFY(!pthread_mutex_lock(m));
}
void unlock()
{
BOOST_VERIFY(!pthread_mutex_unlock(m));
locked=false;
}
~pthread_mutex_scoped_lock()
{
if(locked)
{
unlock();
}
}
};
class pthread_mutex_scoped_unlock
{
pthread_mutex_t* m;
public:
explicit pthread_mutex_scoped_unlock(pthread_mutex_t* m_):
m(m_)
{
BOOST_VERIFY(!pthread_mutex_unlock(m));
}
~pthread_mutex_scoped_unlock()
{
BOOST_VERIFY(!pthread_mutex_lock(m));
}
};
}
}
#include <boost/config/abi_suffix.hpp>
#endif

View File

@@ -1,345 +0,0 @@
#ifndef BOOST_THREAD_PTHREAD_RECURSIVE_MUTEX_HPP
#define BOOST_THREAD_PTHREAD_RECURSIVE_MUTEX_HPP
// (C) Copyright 2007-8 Anthony Williams
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <pthread.h>
#include <boost/utility.hpp>
#include <boost/throw_exception.hpp>
#include <boost/thread/exceptions.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/thread_time.hpp>
#include <boost/assert.hpp>
#ifndef _WIN32
#include <unistd.h>
#endif
#include <boost/date_time/posix_time/conversion.hpp>
#include <errno.h>
#include "timespec.hpp"
#include "pthread_mutex_scoped_lock.hpp"
#ifdef _POSIX_TIMEOUTS
#if _POSIX_TIMEOUTS >= 0
#define BOOST_PTHREAD_HAS_TIMEDLOCK
#endif
#endif
#if defined(BOOST_PTHREAD_HAS_MUTEXATTR_SETTYPE) && defined(BOOST_PTHREAD_HAS_TIMEDLOCK)
#define BOOST_USE_PTHREAD_RECURSIVE_TIMEDLOCK
#endif
#include <boost/config/abi_prefix.hpp>
namespace boost
{
class recursive_mutex
{
private:
recursive_mutex(recursive_mutex const&);
recursive_mutex& operator=(recursive_mutex const&);
pthread_mutex_t m;
#ifndef BOOST_PTHREAD_HAS_MUTEXATTR_SETTYPE
pthread_cond_t cond;
bool is_locked;
pthread_t owner;
unsigned count;
#endif
public:
recursive_mutex()
{
#ifdef BOOST_PTHREAD_HAS_MUTEXATTR_SETTYPE
pthread_mutexattr_t attr;
int const init_attr_res=pthread_mutexattr_init(&attr);
if(init_attr_res)
{
boost::throw_exception(thread_resource_error());
}
int const set_attr_res=pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
if(set_attr_res)
{
BOOST_VERIFY(!pthread_mutexattr_destroy(&attr));
boost::throw_exception(thread_resource_error());
}
int const res=pthread_mutex_init(&m,&attr);
if(res)
{
BOOST_VERIFY(!pthread_mutexattr_destroy(&attr));
boost::throw_exception(thread_resource_error());
}
BOOST_VERIFY(!pthread_mutexattr_destroy(&attr));
#else
int const res=pthread_mutex_init(&m,NULL);
if(res)
{
boost::throw_exception(thread_resource_error());
}
int const res2=pthread_cond_init(&cond,NULL);
if(res2)
{
BOOST_VERIFY(!pthread_mutex_destroy(&m));
boost::throw_exception(thread_resource_error());
}
is_locked=false;
count=0;
#endif
}
~recursive_mutex()
{
BOOST_VERIFY(!pthread_mutex_destroy(&m));
#ifndef BOOST_PTHREAD_HAS_MUTEXATTR_SETTYPE
BOOST_VERIFY(!pthread_cond_destroy(&cond));
#endif
}
#ifdef BOOST_PTHREAD_HAS_MUTEXATTR_SETTYPE
void lock()
{
BOOST_VERIFY(!pthread_mutex_lock(&m));
}
void unlock()
{
BOOST_VERIFY(!pthread_mutex_unlock(&m));
}
bool try_lock()
{
int const res=pthread_mutex_trylock(&m);
BOOST_ASSERT(!res || res==EBUSY);
return !res;
}
typedef pthread_mutex_t* native_handle_type;
native_handle_type native_handle()
{
return &m;
}
#else
void lock()
{
boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
if(is_locked && pthread_equal(owner,pthread_self()))
{
++count;
return;
}
while(is_locked)
{
BOOST_VERIFY(!pthread_cond_wait(&cond,&m));
}
is_locked=true;
++count;
owner=pthread_self();
}
void unlock()
{
boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
if(!--count)
{
is_locked=false;
}
BOOST_VERIFY(!pthread_cond_signal(&cond));
}
bool try_lock()
{
boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
if(is_locked && !pthread_equal(owner,pthread_self()))
{
return false;
}
is_locked=true;
++count;
owner=pthread_self();
return true;
}
#endif
typedef unique_lock<recursive_mutex> scoped_lock;
typedef detail::try_lock_wrapper<recursive_mutex> scoped_try_lock;
};
typedef recursive_mutex recursive_try_mutex;
class recursive_timed_mutex
{
private:
recursive_timed_mutex(recursive_timed_mutex const&);
recursive_timed_mutex& operator=(recursive_timed_mutex const&);
private:
pthread_mutex_t m;
#ifndef BOOST_USE_PTHREAD_RECURSIVE_TIMEDLOCK
pthread_cond_t cond;
bool is_locked;
pthread_t owner;
unsigned count;
#endif
public:
recursive_timed_mutex()
{
#ifdef BOOST_USE_PTHREAD_RECURSIVE_TIMEDLOCK
pthread_mutexattr_t attr;
int const init_attr_res=pthread_mutexattr_init(&attr);
if(init_attr_res)
{
boost::throw_exception(thread_resource_error());
}
int const set_attr_res=pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
if(set_attr_res)
{
boost::throw_exception(thread_resource_error());
}
int const res=pthread_mutex_init(&m,&attr);
if(res)
{
BOOST_VERIFY(!pthread_mutexattr_destroy(&attr));
boost::throw_exception(thread_resource_error());
}
BOOST_VERIFY(!pthread_mutexattr_destroy(&attr));
#else
int const res=pthread_mutex_init(&m,NULL);
if(res)
{
boost::throw_exception(thread_resource_error());
}
int const res2=pthread_cond_init(&cond,NULL);
if(res2)
{
BOOST_VERIFY(!pthread_mutex_destroy(&m));
boost::throw_exception(thread_resource_error());
}
is_locked=false;
count=0;
#endif
}
~recursive_timed_mutex()
{
BOOST_VERIFY(!pthread_mutex_destroy(&m));
#ifndef BOOST_USE_PTHREAD_RECURSIVE_TIMEDLOCK
BOOST_VERIFY(!pthread_cond_destroy(&cond));
#endif
}
template<typename TimeDuration>
bool timed_lock(TimeDuration const & relative_time)
{
return timed_lock(get_system_time()+relative_time);
}
#ifdef BOOST_USE_PTHREAD_RECURSIVE_TIMEDLOCK
void lock()
{
BOOST_VERIFY(!pthread_mutex_lock(&m));
}
void unlock()
{
BOOST_VERIFY(!pthread_mutex_unlock(&m));
}
bool try_lock()
{
int const res=pthread_mutex_trylock(&m);
BOOST_ASSERT(!res || res==EBUSY);
return !res;
}
bool timed_lock(system_time const & abs_time)
{
struct timespec const timeout=detail::get_timespec(abs_time);
int const res=pthread_mutex_timedlock(&m,&timeout);
BOOST_ASSERT(!res || res==ETIMEDOUT);
return !res;
}
typedef pthread_mutex_t* native_handle_type;
native_handle_type native_handle()
{
return &m;
}
#else
void lock()
{
boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
if(is_locked && pthread_equal(owner,pthread_self()))
{
++count;
return;
}
while(is_locked)
{
BOOST_VERIFY(!pthread_cond_wait(&cond,&m));
}
is_locked=true;
++count;
owner=pthread_self();
}
void unlock()
{
boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
if(!--count)
{
is_locked=false;
}
BOOST_VERIFY(!pthread_cond_signal(&cond));
}
bool try_lock()
{
boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
if(is_locked && !pthread_equal(owner,pthread_self()))
{
return false;
}
is_locked=true;
++count;
owner=pthread_self();
return true;
}
bool timed_lock(system_time const & abs_time)
{
struct timespec const timeout=detail::get_timespec(abs_time);
boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
if(is_locked && pthread_equal(owner,pthread_self()))
{
++count;
return true;
}
while(is_locked)
{
int const cond_res=pthread_cond_timedwait(&cond,&m,&timeout);
if(cond_res==ETIMEDOUT)
{
return false;
}
BOOST_ASSERT(!cond_res);
}
is_locked=true;
++count;
owner=pthread_self();
return true;
}
#endif
typedef unique_lock<recursive_timed_mutex> scoped_timed_lock;
typedef detail::try_lock_wrapper<recursive_timed_mutex> scoped_try_lock;
typedef scoped_timed_lock scoped_lock;
};
}
#include <boost/config/abi_suffix.hpp>
#endif

View File

@@ -1,303 +0,0 @@
#ifndef BOOST_THREAD_PTHREAD_SHARED_MUTEX_HPP
#define BOOST_THREAD_PTHREAD_SHARED_MUTEX_HPP
// (C) Copyright 2006-8 Anthony Williams
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/assert.hpp>
#include <boost/static_assert.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/detail/thread_interruption.hpp>
#include <boost/config/abi_prefix.hpp>
namespace boost
{
class shared_mutex
{
private:
struct state_data
{
unsigned shared_count;
bool exclusive;
bool upgrade;
bool exclusive_waiting_blocked;
};
state_data state;
boost::mutex state_change;
boost::condition_variable shared_cond;
boost::condition_variable exclusive_cond;
boost::condition_variable upgrade_cond;
void release_waiters()
{
exclusive_cond.notify_one();
shared_cond.notify_all();
}
public:
shared_mutex()
{
state_data state_={0,0,0,0};
state=state_;
}
~shared_mutex()
{
}
void lock_shared()
{
boost::this_thread::disable_interruption do_not_disturb;
boost::mutex::scoped_lock lk(state_change);
while(state.exclusive || state.exclusive_waiting_blocked)
{
shared_cond.wait(lk);
}
++state.shared_count;
}
bool try_lock_shared()
{
boost::mutex::scoped_lock lk(state_change);
if(state.exclusive || state.exclusive_waiting_blocked)
{
return false;
}
else
{
++state.shared_count;
return true;
}
}
bool timed_lock_shared(system_time const& timeout)
{
boost::this_thread::disable_interruption do_not_disturb;
boost::mutex::scoped_lock lk(state_change);
while(state.exclusive || state.exclusive_waiting_blocked)
{
if(!shared_cond.timed_wait(lk,timeout))
{
return false;
}
}
++state.shared_count;
return true;
}
template<typename TimeDuration>
bool timed_lock_shared(TimeDuration const & relative_time)
{
return timed_lock_shared(get_system_time()+relative_time);
}
void unlock_shared()
{
boost::mutex::scoped_lock lk(state_change);
bool const last_reader=!--state.shared_count;
if(last_reader)
{
if(state.upgrade)
{
state.upgrade=false;
state.exclusive=true;
upgrade_cond.notify_one();
}
else
{
state.exclusive_waiting_blocked=false;
}
release_waiters();
}
}
void lock()
{
boost::this_thread::disable_interruption do_not_disturb;
boost::mutex::scoped_lock lk(state_change);
while(state.shared_count || state.exclusive)
{
state.exclusive_waiting_blocked=true;
exclusive_cond.wait(lk);
}
state.exclusive=true;
}
bool timed_lock(system_time const& timeout)
{
boost::this_thread::disable_interruption do_not_disturb;
boost::mutex::scoped_lock lk(state_change);
while(state.shared_count || state.exclusive)
{
state.exclusive_waiting_blocked=true;
if(!exclusive_cond.timed_wait(lk,timeout))
{
if(state.shared_count || state.exclusive)
{
state.exclusive_waiting_blocked=false;
exclusive_cond.notify_one();
return false;
}
break;
}
}
state.exclusive=true;
return true;
}
template<typename TimeDuration>
bool timed_lock(TimeDuration const & relative_time)
{
return timed_lock(get_system_time()+relative_time);
}
bool try_lock()
{
boost::mutex::scoped_lock lk(state_change);
if(state.shared_count || state.exclusive)
{
return false;
}
else
{
state.exclusive=true;
return true;
}
}
void unlock()
{
boost::mutex::scoped_lock lk(state_change);
state.exclusive=false;
state.exclusive_waiting_blocked=false;
release_waiters();
}
void lock_upgrade()
{
boost::this_thread::disable_interruption do_not_disturb;
boost::mutex::scoped_lock lk(state_change);
while(state.exclusive || state.exclusive_waiting_blocked || state.upgrade)
{
shared_cond.wait(lk);
}
++state.shared_count;
state.upgrade=true;
}
bool timed_lock_upgrade(system_time const& timeout)
{
boost::this_thread::disable_interruption do_not_disturb;
boost::mutex::scoped_lock lk(state_change);
while(state.exclusive || state.exclusive_waiting_blocked || state.upgrade)
{
if(!shared_cond.timed_wait(lk,timeout))
{
if(state.exclusive || state.exclusive_waiting_blocked || state.upgrade)
{
return false;
}
break;
}
}
++state.shared_count;
state.upgrade=true;
return true;
}
template<typename TimeDuration>
bool timed_lock_upgrade(TimeDuration const & relative_time)
{
return timed_lock_upgrade(get_system_time()+relative_time);
}
bool try_lock_upgrade()
{
boost::mutex::scoped_lock lk(state_change);
if(state.exclusive || state.exclusive_waiting_blocked || state.upgrade)
{
return false;
}
else
{
++state.shared_count;
state.upgrade=true;
return true;
}
}
void unlock_upgrade()
{
boost::mutex::scoped_lock lk(state_change);
state.upgrade=false;
bool const last_reader=!--state.shared_count;
if(last_reader)
{
state.exclusive_waiting_blocked=false;
release_waiters();
}
}
void unlock_upgrade_and_lock()
{
boost::this_thread::disable_interruption do_not_disturb;
boost::mutex::scoped_lock lk(state_change);
--state.shared_count;
while(state.shared_count)
{
upgrade_cond.wait(lk);
}
state.upgrade=false;
state.exclusive=true;
}
void unlock_and_lock_upgrade()
{
boost::mutex::scoped_lock lk(state_change);
state.exclusive=false;
state.upgrade=true;
++state.shared_count;
state.exclusive_waiting_blocked=false;
release_waiters();
}
void unlock_and_lock_shared()
{
boost::mutex::scoped_lock lk(state_change);
state.exclusive=false;
++state.shared_count;
state.exclusive_waiting_blocked=false;
release_waiters();
}
void unlock_upgrade_and_lock_shared()
{
boost::mutex::scoped_lock lk(state_change);
state.upgrade=false;
state.exclusive_waiting_blocked=false;
release_waiters();
}
};
}
#include <boost/config/abi_suffix.hpp>
#endif

View File

@@ -1,145 +0,0 @@
#ifndef BOOST_THREAD_PTHREAD_THREAD_DATA_HPP
#define BOOST_THREAD_PTHREAD_THREAD_DATA_HPP
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// (C) Copyright 2007 Anthony Williams
#include <boost/thread/detail/config.hpp>
#include <boost/thread/exceptions.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/optional.hpp>
#include <pthread.h>
#include <boost/assert.hpp>
#include "condition_variable_fwd.hpp"
#include <map>
#include <boost/config/abi_prefix.hpp>
namespace boost
{
class thread;
namespace detail
{
struct tss_cleanup_function;
struct thread_exit_callback_node;
struct tss_data_node
{
boost::shared_ptr<boost::detail::tss_cleanup_function> func;
void* value;
tss_data_node(boost::shared_ptr<boost::detail::tss_cleanup_function> func_,
void* value_):
func(func_),value(value_)
{}
};
struct thread_data_base;
typedef boost::shared_ptr<thread_data_base> thread_data_ptr;
struct BOOST_THREAD_DECL thread_data_base:
enable_shared_from_this<thread_data_base>
{
thread_data_ptr self;
pthread_t thread_handle;
boost::mutex data_mutex;
boost::condition_variable done_condition;
boost::mutex sleep_mutex;
boost::condition_variable sleep_condition;
bool done;
bool join_started;
bool joined;
boost::detail::thread_exit_callback_node* thread_exit_callbacks;
std::map<void const*,boost::detail::tss_data_node> tss_data;
bool interrupt_enabled;
bool interrupt_requested;
pthread_mutex_t* cond_mutex;
pthread_cond_t* current_cond;
thread_data_base():
done(false),join_started(false),joined(false),
thread_exit_callbacks(0),
interrupt_enabled(true),
interrupt_requested(false),
current_cond(0)
{}
virtual ~thread_data_base();
typedef pthread_t native_handle_type;
virtual void run()=0;
};
BOOST_THREAD_DECL thread_data_base* get_current_thread_data();
class interruption_checker
{
thread_data_base* const thread_info;
pthread_mutex_t* m;
bool set;
void check_for_interruption()
{
if(thread_info->interrupt_requested)
{
thread_info->interrupt_requested=false;
throw thread_interrupted();
}
}
void operator=(interruption_checker&);
public:
explicit interruption_checker(pthread_mutex_t* cond_mutex,pthread_cond_t* cond):
thread_info(detail::get_current_thread_data()),m(cond_mutex),
set(thread_info && thread_info->interrupt_enabled)
{
if(set)
{
lock_guard<mutex> guard(thread_info->data_mutex);
check_for_interruption();
thread_info->cond_mutex=cond_mutex;
thread_info->current_cond=cond;
BOOST_VERIFY(!pthread_mutex_lock(m));
}
else
{
BOOST_VERIFY(!pthread_mutex_lock(m));
}
}
~interruption_checker()
{
if(set)
{
BOOST_VERIFY(!pthread_mutex_unlock(m));
lock_guard<mutex> guard(thread_info->data_mutex);
thread_info->cond_mutex=NULL;
thread_info->current_cond=NULL;
}
else
{
BOOST_VERIFY(!pthread_mutex_unlock(m));
}
}
};
}
namespace this_thread
{
void BOOST_THREAD_DECL yield();
void BOOST_THREAD_DECL sleep(system_time const& abs_time);
template<typename TimeDuration>
inline void sleep(TimeDuration const& rel_time)
{
this_thread::sleep(get_system_time()+rel_time);
}
}
}
#include <boost/config/abi_suffix.hpp>
#endif

View File

@@ -1,242 +0,0 @@
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// (C) Copyright 2008 Anthony Williams
#ifndef THREAD_HEAP_ALLOC_PTHREAD_HPP
#define THREAD_HEAP_ALLOC_PTHREAD_HPP
#include <boost/config/abi_prefix.hpp>
namespace boost
{
namespace detail
{
template<typename T>
inline T* heap_new()
{
return new T();
}
#ifndef BOOST_NO_RVALUE_REFERENCES
template<typename T,typename A1>
inline T* heap_new(A1&& a1)
{
return new T(static_cast<A1&&>(a1));
}
template<typename T,typename A1,typename A2>
inline T* heap_new(A1&& a1,A2&& a2)
{
return new T(static_cast<A1&&>(a1),static_cast<A2&&>(a2));
}
template<typename T,typename A1,typename A2,typename A3>
inline T* heap_new(A1&& a1,A2&& a2,A3&& a3)
{
return new T(static_cast<A1&&>(a1),static_cast<A2&&>(a2),
static_cast<A3&&>(a3));
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1&& a1,A2&& a2,A3&& a3,A4&& a4)
{
return new T(static_cast<A1&&>(a1),static_cast<A2&&>(a2),
static_cast<A3&&>(a3),static_cast<A4&&>(a4));
}
#else
template<typename T,typename A1>
inline T* heap_new_impl(A1 a1)
{
return new T(a1);
}
template<typename T,typename A1,typename A2>
inline T* heap_new_impl(A1 a1,A2 a2)
{
return new T(a1,a2);
}
template<typename T,typename A1,typename A2,typename A3>
inline T* heap_new_impl(A1 a1,A2 a2,A3 a3)
{
return new T(a1,a2,a3);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new_impl(A1 a1,A2 a2,A3 a3,A4 a4)
{
return new T(a1,a2,a3,a4);
}
template<typename T,typename A1>
inline T* heap_new(A1 const& a1)
{
return heap_new_impl<T,A1 const&>(a1);
}
template<typename T,typename A1>
inline T* heap_new(A1& a1)
{
return heap_new_impl<T,A1&>(a1);
}
template<typename T,typename A1,typename A2>
inline T* heap_new(A1 const& a1,A2 const& a2)
{
return heap_new_impl<T,A1 const&,A2 const&>(a1,a2);
}
template<typename T,typename A1,typename A2>
inline T* heap_new(A1& a1,A2 const& a2)
{
return heap_new_impl<T,A1&,A2 const&>(a1,a2);
}
template<typename T,typename A1,typename A2>
inline T* heap_new(A1 const& a1,A2& a2)
{
return heap_new_impl<T,A1 const&,A2&>(a1,a2);
}
template<typename T,typename A1,typename A2>
inline T* heap_new(A1& a1,A2& a2)
{
return heap_new_impl<T,A1&,A2&>(a1,a2);
}
template<typename T,typename A1,typename A2,typename A3>
inline T* heap_new(A1 const& a1,A2 const& a2,A3 const& a3)
{
return heap_new_impl<T,A1 const&,A2 const&,A3 const&>(a1,a2,a3);
}
template<typename T,typename A1,typename A2,typename A3>
inline T* heap_new(A1& a1,A2 const& a2,A3 const& a3)
{
return heap_new_impl<T,A1&,A2 const&,A3 const&>(a1,a2,a3);
}
template<typename T,typename A1,typename A2,typename A3>
inline T* heap_new(A1 const& a1,A2& a2,A3 const& a3)
{
return heap_new_impl<T,A1 const&,A2&,A3 const&>(a1,a2,a3);
}
template<typename T,typename A1,typename A2,typename A3>
inline T* heap_new(A1& a1,A2& a2,A3 const& a3)
{
return heap_new_impl<T,A1&,A2&,A3 const&>(a1,a2,a3);
}
template<typename T,typename A1,typename A2,typename A3>
inline T* heap_new(A1 const& a1,A2 const& a2,A3& a3)
{
return heap_new_impl<T,A1 const&,A2 const&,A3&>(a1,a2,a3);
}
template<typename T,typename A1,typename A2,typename A3>
inline T* heap_new(A1& a1,A2 const& a2,A3& a3)
{
return heap_new_impl<T,A1&,A2 const&,A3&>(a1,a2,a3);
}
template<typename T,typename A1,typename A2,typename A3>
inline T* heap_new(A1 const& a1,A2& a2,A3& a3)
{
return heap_new_impl<T,A1 const&,A2&,A3&>(a1,a2,a3);
}
template<typename T,typename A1,typename A2,typename A3>
inline T* heap_new(A1& a1,A2& a2,A3& a3)
{
return heap_new_impl<T,A1&,A2&,A3&>(a1,a2,a3);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1 const& a1,A2 const& a2,A3 const& a3,A4 const& a4)
{
return heap_new_impl<T,A1 const&,A2 const&,A3 const&,A4 const&>(a1,a2,a3,a4);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1& a1,A2 const& a2,A3 const& a3,A4 const& a4)
{
return heap_new_impl<T,A1&,A2 const&,A3 const&,A4 const&>(a1,a2,a3,a4);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1 const& a1,A2& a2,A3 const& a3,A4 const& a4)
{
return heap_new_impl<T,A1 const&,A2&,A3 const&,A4 const&>(a1,a2,a3,a4);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1& a1,A2& a2,A3 const& a3,A4 const& a4)
{
return heap_new_impl<T,A1&,A2&,A3 const&,A4 const&>(a1,a2,a3,a4);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1 const& a1,A2 const& a2,A3& a3,A4 const& a4)
{
return heap_new_impl<T,A1 const&,A2 const&,A3&,A4 const&>(a1,a2,a3,a4);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1& a1,A2 const& a2,A3& a3,A4 const& a4)
{
return heap_new_impl<T,A1&,A2 const&,A3&,A4 const&>(a1,a2,a3,a4);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1 const& a1,A2& a2,A3& a3,A4 const& a4)
{
return heap_new_impl<T,A1 const&,A2&,A3&,A4 const&>(a1,a2,a3,a4);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1& a1,A2& a2,A3& a3,A4 const& a4)
{
return heap_new_impl<T,A1&,A2&,A3&,A4 const&>(a1,a2,a3,a4);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1 const& a1,A2 const& a2,A3 const& a3,A4& a4)
{
return heap_new_impl<T,A1 const&,A2 const&,A3 const&,A4&>(a1,a2,a3,a4);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1& a1,A2 const& a2,A3 const& a3,A4& a4)
{
return heap_new_impl<T,A1&,A2 const&,A3 const&,A4&>(a1,a2,a3,a4);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1 const& a1,A2& a2,A3 const& a3,A4& a4)
{
return heap_new_impl<T,A1 const&,A2&,A3 const&,A4&>(a1,a2,a3,a4);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1& a1,A2& a2,A3 const& a3,A4& a4)
{
return heap_new_impl<T,A1&,A2&,A3 const&,A4&>(a1,a2,a3,a4);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1 const& a1,A2 const& a2,A3& a3,A4& a4)
{
return heap_new_impl<T,A1 const&,A2 const&,A3&,A4&>(a1,a2,a3,a4);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1& a1,A2 const& a2,A3& a3,A4& a4)
{
return heap_new_impl<T,A1&,A2 const&,A3&,A4&>(a1,a2,a3,a4);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1 const& a1,A2& a2,A3& a3,A4& a4)
{
return heap_new_impl<T,A1 const&,A2&,A3&,A4&>(a1,a2,a3,a4);
}
template<typename T,typename A1,typename A2,typename A3,typename A4>
inline T* heap_new(A1& a1,A2& a2,A3& a3,A4& a4)
{
return heap_new_impl<T,A1&,A2&,A3&,A4&>(a1,a2,a3,a4);
}
#endif
template<typename T>
inline void heap_delete(T* data)
{
delete data;
}
template<typename T>
struct do_heap_delete
{
void operator()(T* data) const
{
detail::heap_delete(data);
}
};
}
}
#include <boost/config/abi_suffix.hpp>
#endif

View File

@@ -1,36 +0,0 @@
#ifndef BOOST_THREAD_PTHREAD_TIMESPEC_HPP
#define BOOST_THREAD_PTHREAD_TIMESPEC_HPP
// (C) Copyright 2007-8 Anthony Williams
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/thread/thread_time.hpp>
#include <boost/date_time/posix_time/conversion.hpp>
#include <pthread.h>
#ifndef _WIN32
#include <unistd.h>
#endif
#include <boost/config/abi_prefix.hpp>
namespace boost
{
namespace detail
{
inline struct timespec get_timespec(boost::system_time const& abs_time)
{
struct timespec timeout={0,0};
boost::posix_time::time_duration const time_since_epoch=abs_time-boost::posix_time::from_time_t(0);
timeout.tv_sec=time_since_epoch.total_seconds();
timeout.tv_nsec=(long)(time_since_epoch.fractional_seconds()*(1000000000l/time_since_epoch.ticks_per_second()));
return timeout;
}
}
}
#include <boost/config/abi_suffix.hpp>
#endif

Some files were not shown because too many files have changed in this diff Show More