Files
oldlinux-files/Ref-docs/POSIX/susv3/functions/pthread_cond_timedwait.html
2024-02-19 00:21:47 -05:00

324 lines
18 KiB
HTML

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta name="generator" content="HTML Tidy, see www.w3.org">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="style.css"><!-- Generated by The Open Group's rhtm tool v1.2.1 -->
<!-- Copyright (c) 2001 The Open Group, All Rights Reserved -->
<title>pthread_cond_timedwait</title>
</head>
<body bgcolor="white">
<script type="text/javascript" language="JavaScript" src="../jscript/codes.js">
</script>
<basefont size="3"> <a name="pthread_cond_timedwait"></a> <a name="tag_03_518"></a><!-- pthread_cond_timedwait -->
<!--header start-->
<center><font size="2">The Open Group Base Specifications Issue 6<br>
IEEE Std 1003.1-2001<br>
Copyright &copy; 2001 The IEEE and The Open Group, All Rights reserved.</font></center>
<!--header end-->
<hr size="2" noshade>
<h4><a name="tag_03_518_01"></a>NAME</h4>
<blockquote>pthread_cond_timedwait, pthread_cond_wait - wait on a condition</blockquote>
<h4><a name="tag_03_518_02"></a>SYNOPSIS</h4>
<blockquote class="synopsis">
<div class="box"><code><tt><sup>[<a href="javascript:open_code('THR')">THR</a>]</sup> <img src="../images/opt-start.gif" alt=
"[Option Start]" border="0"> #include &lt;<a href="../basedefs/pthread.h.html">pthread.h</a>&gt;<br>
<br>
int pthread_cond_timedwait(pthread_cond_t *restrict</tt> <i>cond</i><tt>,<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; pthread_mutex_t *restrict</tt> <i>mutex</i><tt>,<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; const struct timespec *restrict</tt> <i>abstime</i><tt>);<br>
int pthread_cond_wait(pthread_cond_t *restrict</tt> <i>cond</i><tt>,<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; pthread_mutex_t *restrict</tt> <i>mutex</i><tt>); <img src="../images/opt-end.gif" alt=
"[Option End]" border="0"></tt></code></div>
<tt><br>
</tt></blockquote>
<h4><a name="tag_03_518_03"></a>DESCRIPTION</h4>
<blockquote>
<p>The <i>pthread_cond_timedwait</i>() and <i>pthread_cond_wait</i>() functions shall block on a condition variable. They shall be
called with <i>mutex</i> locked by the calling thread or undefined behavior results.</p>
<p>These functions atomically release <i>mutex</i> and cause the calling thread to block on the condition variable <i>cond</i>;
atomically here means &quot;atomically with respect to access by another thread to the mutex and then the condition variable&quot;. That
is, if another thread is able to acquire the mutex after the about-to-block thread has released it, then a subsequent call to <a
href="../functions/pthread_cond_broadcast.html"><i>pthread_cond_broadcast</i>()</a> or <a href=
"../functions/pthread_cond_signal.html"><i>pthread_cond_signal</i>()</a> in that thread shall behave as if it were issued after the
about-to-block thread has blocked.</p>
<p>Upon successful return, the mutex shall have been locked and shall be owned by the calling thread.</p>
<p>When using condition variables there is always a Boolean predicate involving shared variables associated with each condition
wait that is true if the thread should proceed. Spurious wakeups from the <i>pthread_cond_timedwait</i>() or
<i>pthread_cond_wait</i>() functions may occur. Since the return from <i>pthread_cond_timedwait</i>() or <i>pthread_cond_wait</i>()
does not imply anything about the value of this predicate, the predicate should be re-evaluated upon such return.</p>
<p>The effect of using more than one mutex for concurrent <i>pthread_cond_timedwait</i>() or <i>pthread_cond_wait</i>() operations
on the same condition variable is undefined; that is, a condition variable becomes bound to a unique mutex when a thread waits on
the condition variable, and this (dynamic) binding shall end when the wait returns.</p>
<p>A condition wait (whether timed or not) is a cancelation point. When the cancelability enable state of a thread is set to
PTHREAD_CANCEL_DEFERRED, a side effect of acting upon a cancelation request while in a condition wait is that the mutex is (in
effect) re-acquired before calling the first cancelation cleanup handler. The effect is as if the thread were unblocked, allowed to
execute up to the point of returning from the call to <i>pthread_cond_timedwait</i>() or <i>pthread_cond_wait</i>(), but at that
point notices the cancelation request and instead of returning to the caller of <i>pthread_cond_timedwait</i>() or
<i>pthread_cond_wait</i>(), starts the thread cancelation activities, which includes calling cancelation cleanup handlers.</p>
<p>A thread that has been unblocked because it has been canceled while blocked in a call to <i>pthread_cond_timedwait</i>() or
<i>pthread_cond_wait</i>() shall not consume any condition signal that may be directed concurrently at the condition variable if
there are other threads blocked on the condition variable.</p>
<p>The <i>pthread_cond_timedwait</i>() function shall be equivalent to <i>pthread_cond_wait</i>(), except that an error is returned
if the absolute time specified by <i>abstime</i> passes (that is, system time equals or exceeds <i>abstime</i>) before the
condition <i>cond</i> is signaled or broadcasted, or if the absolute time specified by <i>abstime</i> has already been passed at
the time of the call.</p>
<p><sup>[<a href="javascript:open_code('CS')">CS</a>]</sup> <img src="../images/opt-start.gif" alt="[Option Start]" border="0"> If
the Clock Selection option is supported, the condition variable shall have a clock attribute which specifies the clock that shall
be used to measure the time specified by the <i>abstime</i> argument. <img src="../images/opt-end.gif" alt="[Option End]" border=
"0"> When such timeouts occur, <i>pthread_cond_timedwait</i>() shall nonetheless release and re-acquire the mutex referenced by
<i>mutex</i>. The <i>pthread_cond_timedwait</i>() function is also a cancelation point.</p>
<p>If a signal is delivered to a thread waiting for a condition variable, upon return from the signal handler the thread resumes
waiting for the condition variable as if it was not interrupted, or it shall return zero due to spurious wakeup.</p>
</blockquote>
<h4><a name="tag_03_518_04"></a>RETURN VALUE</h4>
<blockquote>
<p>Except in the case of [ETIMEDOUT], all these error checks shall act as if they were performed immediately at the beginning of
processing for the function and shall cause an error return, in effect, prior to modifying the state of the mutex specified by
<i>mutex</i> or the condition variable specified by <i>cond</i>.</p>
<p>Upon successful completion, a value of zero shall be returned; otherwise, an error number shall be returned to indicate the
error.</p>
</blockquote>
<h4><a name="tag_03_518_05"></a>ERRORS</h4>
<blockquote>
<p>The <i>pthread_cond_timedwait</i>() function shall fail if:</p>
<dl compact>
<dt>[ETIMEDOUT]</dt>
<dd>The time specified by <i>abstime</i> to <i>pthread_cond_timedwait</i>() has passed.</dd>
</dl>
<p>The <i>pthread_cond_timedwait</i>() and <i>pthread_cond_wait</i>() functions may fail if:</p>
<dl compact>
<dt>[EINVAL]</dt>
<dd>The value specified by <i>cond</i>, <i>mutex</i>, or <i>abstime</i> is invalid.</dd>
<dt>[EINVAL]</dt>
<dd>Different mutexes were supplied for concurrent <i>pthread_cond_timedwait</i>() or <i>pthread_cond_wait</i>() operations on the
same condition variable.</dd>
<dt>[EPERM]</dt>
<dd>The mutex was not owned by the current thread at the time of the call.</dd>
</dl>
<p>These functions shall not return an error code of [EINTR].</p>
</blockquote>
<hr>
<div class="box"><em>The following sections are informative.</em></div>
<h4><a name="tag_03_518_06"></a>EXAMPLES</h4>
<blockquote>
<p>None.</p>
</blockquote>
<h4><a name="tag_03_518_07"></a>APPLICATION USAGE</h4>
<blockquote>
<p>None.</p>
</blockquote>
<h4><a name="tag_03_518_08"></a>RATIONALE</h4>
<blockquote>
<h5><a name="tag_03_518_08_01"></a>Condition Wait Semantics</h5>
<p>It is important to note that when <i>pthread_cond_wait</i>() and <i>pthread_cond_timedwait</i>() return without error, the
associated predicate may still be false. Similarly, when <i>pthread_cond_timedwait</i>() returns with the timeout error, the
associated predicate may be true due to an unavoidable race between the expiration of the timeout and the predicate state
change.</p>
<p>Some implementations, particularly on a multi-processor, may sometimes cause multiple threads to wake up when the condition
variable is signaled simultaneously on different processors.</p>
<p>In general, whenever a condition wait returns, the thread has to re-evaluate the predicate associated with the condition wait to
determine whether it can safely proceed, should wait again, or should declare a timeout. A return from the wait does not imply that
the associated predicate is either true or false.</p>
<p>It is thus recommended that a condition wait be enclosed in the equivalent of a &quot;while loop&quot; that checks the predicate.</p>
<h5><a name="tag_03_518_08_02"></a>Timed Wait Semantics</h5>
<p>An absolute time measure was chosen for specifying the timeout parameter for two reasons. First, a relative time measure can be
easily implemented on top of a function that specifies absolute time, but there is a race condition associated with specifying an
absolute timeout on top of a function that specifies relative timeouts. For example, assume that <a href=
"../functions/clock_gettime.html"><i>clock_gettime</i>()</a> returns the current time and <i>cond_relative_timed_wait</i>() uses
relative timeouts:</p>
<pre>
<tt>clock_gettime(CLOCK_REALTIME, &amp;now)
reltime = sleep_til_this_absolute_time -now;
cond_relative_timed_wait(c, m, &amp;reltime);
</tt>
</pre>
<p>If the thread is preempted between the first statement and the last statement, the thread blocks for too long. Blocking,
however, is irrelevant if an absolute timeout is used. An absolute timeout also need not be recomputed if it is used multiple times
in a loop, such as that enclosing a condition wait.</p>
<p>For cases when the system clock is advanced discontinuously by an operator, it is expected that implementations process any
timed wait expiring at an intervening time as if that time had actually occurred.</p>
<h5><a name="tag_03_518_08_03"></a>Cancelation and Condition Wait</h5>
<p>A condition wait, whether timed or not, is a cancelation point. That is, the functions <i>pthread_cond_wait</i>() or
<i>pthread_cond_timedwait</i>() are points where a pending (or concurrent) cancelation request is noticed. The reason for this is
that an indefinite wait is possible at these points-whatever event is being waited for, even if the program is totally correct,
might never occur; for example, some input data being awaited might never be sent. By making condition wait a cancelation point,
the thread can be canceled and perform its cancelation cleanup handler even though it may be stuck in some indefinite wait.</p>
<p>A side effect of acting on a cancelation request while a thread is blocked on a condition variable is to re-acquire the mutex
before calling any of the cancelation cleanup handlers. This is done in order to ensure that the cancelation cleanup handler is
executed in the same state as the critical code that lies both before and after the call to the condition wait function. This rule
is also required when interfacing to POSIX threads from languages, such as Ada or C++, which may choose to map cancelation onto a
language exception; this rule ensures that each exception handler guarding a critical section can always safely depend upon the
fact that the associated mutex has already been locked regardless of exactly where within the critical section the exception was
raised. Without this rule, there would not be a uniform rule that exception handlers could follow regarding the lock, and so coding
would become very cumbersome.</p>
<p>Therefore, since <i>some</i> statement has to be made regarding the state of the lock when a cancelation is delivered during a
wait, a definition has been chosen that makes application coding most convenient and error free.</p>
<p>When acting on a cancelation request while a thread is blocked on a condition variable, the implementation is required to ensure
that the thread does not consume any condition signals directed at that condition variable if there are any other threads waiting
on that condition variable. This rule is specified in order to avoid deadlock conditions that could occur if these two independent
requests (one acting on a thread and the other acting on the condition variable) were not processed independently.</p>
<h5><a name="tag_03_518_08_04"></a>Performance of Mutexes and Condition Variables</h5>
<p>Mutexes are expected to be locked only for a few instructions. This practice is almost automatically enforced by the desire of
programmers to avoid long serial regions of execution (which would reduce total effective parallelism).</p>
<p>When using mutexes and condition variables, one tries to ensure that the usual case is to lock the mutex, access shared data,
and unlock the mutex. Waiting on a condition variable should be a relatively rare situation. For example, when implementing a
read-write lock, code that acquires a read-lock typically needs only to increment the count of readers (under mutual-exclusion) and
return. The calling thread would actually wait on the condition variable only when there is already an active writer. So the
efficiency of a synchronization operation is bounded by the cost of mutex lock/unlock and not by condition wait. Note that in the
usual case there is no context switch.</p>
<p>This is not to say that the efficiency of condition waiting is unimportant. Since there needs to be at least one context switch
per Ada rendezvous, the efficiency of waiting on a condition variable is important. The cost of waiting on a condition variable
should be little more than the minimal cost for a context switch plus the time to unlock and lock the mutex.</p>
<h5><a name="tag_03_518_08_05"></a>Features of Mutexes and Condition Variables</h5>
<p>It had been suggested that the mutex acquisition and release be decoupled from condition wait. This was rejected because it is
the combined nature of the operation that, in fact, facilitates realtime implementations. Those implementations can atomically move
a high-priority thread between the condition variable and the mutex in a manner that is transparent to the caller. This can prevent
extra context switches and provide more deterministic acquisition of a mutex when the waiting thread is signaled. Thus, fairness
and priority issues can be dealt with directly by the scheduling discipline. Furthermore, the current condition wait operation
matches existing practice.</p>
<h5><a name="tag_03_518_08_06"></a>Scheduling Behavior of Mutexes and Condition Variables</h5>
<p>Synchronization primitives that attempt to interfere with scheduling policy by specifying an ordering rule are considered
undesirable. Threads waiting on mutexes and condition variables are selected to proceed in an order dependent upon the scheduling
policy rather than in some fixed order (for example, FIFO or priority). Thus, the scheduling policy determines which thread(s) are
awakened and allowed to proceed.</p>
<h5><a name="tag_03_518_08_07"></a>Timed Condition Wait</h5>
<p>The <i>pthread_cond_timedwait</i>() function allows an application to give up waiting for a particular condition after a given
amount of time. An example of its use follows:</p>
<pre>
<tt>(void) pthread_mutex_lock(&amp;t.mn);
t.waiters++;
clock_gettime(CLOCK_REALTIME, &amp;ts);
ts.tv_sec += 5;
rc = 0;
while (! mypredicate(&amp;t) &amp;&amp; rc == 0)
rc = pthread_cond_timedwait(&amp;t.cond, &amp;t.mn, &amp;ts);
t.waiters--;
if (rc == 0) setmystate(&amp;t);
(void) pthread_mutex_unlock(&amp;t.mn);
</tt>
</pre>
<p>By making the timeout parameter absolute, it does not need to be recomputed each time the program checks its blocking predicate.
If the timeout was relative, it would have to be recomputed before each call. This would be especially difficult since such code
would need to take into account the possibility of extra wakeups that result from extra broadcasts or signals on the condition
variable that occur before either the predicate is true or the timeout is due.</p>
</blockquote>
<h4><a name="tag_03_518_09"></a>FUTURE DIRECTIONS</h4>
<blockquote>
<p>None.</p>
</blockquote>
<h4><a name="tag_03_518_10"></a>SEE ALSO</h4>
<blockquote>
<p><a href="pthread_cond_signal.html"><i>pthread_cond_signal</i>()</a> , <a href=
"pthread_cond_broadcast.html"><i>pthread_cond_broadcast</i>()</a> , the Base Definitions volume of IEEE&nbsp;Std&nbsp;1003.1-2001,
<a href="../basedefs/pthread.h.html"><i>&lt;pthread.h&gt;</i></a></p>
</blockquote>
<h4><a name="tag_03_518_11"></a>CHANGE HISTORY</h4>
<blockquote>
<p>First released in Issue 5. Included for alignment with the POSIX Threads Extension.</p>
</blockquote>
<h4><a name="tag_03_518_12"></a>Issue 6</h4>
<blockquote>
<p>The <i>pthread_cond_timedwait</i>() and <i>pthread_cond_wait</i>() functions are marked as part of the Threads option.</p>
<p>The Open Group Corrigendum U021/9 is applied, correcting the prototype for the <i>pthread_cond_wait</i>() function.</p>
<p>The DESCRIPTION is updated for alignment with IEEE&nbsp;Std&nbsp;1003.1j-2000 by adding semantics for the Clock Selection
option.</p>
<p>The ERRORS section has an additional case for [EPERM] in response to IEEE PASC Interpretation 1003.1c #28.</p>
<p>The <b>restrict</b> keyword is added to the <i>pthread_cond_timedwait</i>() and <i>pthread_cond_wait</i>() prototypes for
alignment with the ISO/IEC&nbsp;9899:1999 standard.</p>
</blockquote>
<div class="box"><em>End of informative text.</em></div>
<hr>
<hr size="2" noshade>
<center><font size="2"><!--footer start-->
UNIX &reg; is a registered Trademark of The Open Group.<br>
POSIX &reg; is a registered Trademark of The IEEE.<br>
[ <a href="../mindex.html">Main Index</a> | <a href="../basedefs/contents.html">XBD</a> | <a href=
"../utilities/contents.html">XCU</a> | <a href="../functions/contents.html">XSH</a> | <a href="../xrat/contents.html">XRAT</a>
]</font></center>
<!--footer end-->
<hr size="2" noshade>
</body>
</html>