Sigstack is disabled in favour of sigaltstack.
[platform/upstream/pth.git] / pth.pod
1 ##
2 ##  GNU Pth - The GNU Portable Threads
3 ##  Copyright (c) 1999-2006 Ralf S. Engelschall <rse@engelschall.com>
4 ##
5 ##  This file is part of GNU Pth, a non-preemptive thread scheduling
6 ##  library which can be found at http://www.gnu.org/software/pth/.
7 ##
8 ##  This library is free software; you can redistribute it and/or
9 ##  modify it under the terms of the GNU Lesser General Public
10 ##  License as published by the Free Software Foundation; either
11 ##  version 2.1 of the License, or (at your option) any later version.
12 ##
13 ##  This library is distributed in the hope that it will be useful,
14 ##  but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 ##  Lesser General Public License for more details.
17 ##
18 ##  You should have received a copy of the GNU Lesser General Public
19 ##  License along with this library; if not, write to the Free Software
20 ##  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21 ##  USA, or contact Ralf S. Engelschall <rse@engelschall.com>.
22 ##
23 ##  pth.pod: Pth manual page
24 ##
25
26 #                            ``Real programmers don't document.
27 #                              Documentation is for wimps who can't
28 #                              read the listings of the object deck.''
29
30 =pod
31
32 =head1 NAME
33
34 B<pth> - GNU Portable Threads
35
36 =head1 VERSION
37
38 GNU Pth PTH_VERSION_STR
39
40 =head1 SYNOPSIS
41
42 =over 4
43
44 =item B<Global Library Management>
45
46 pth_init,
47 pth_kill,
48 pth_ctrl,
49 pth_version.
50
51 =item B<Thread Attribute Handling>
52
53 pth_attr_of,
54 pth_attr_new,
55 pth_attr_init,
56 pth_attr_set,
57 pth_attr_get,
58 pth_attr_destroy.
59
60 =item B<Thread Control>
61
62 pth_spawn,
63 pth_once,
64 pth_self,
65 pth_suspend,
66 pth_resume,
67 pth_yield,
68 pth_nap,
69 pth_wait,
70 pth_cancel,
71 pth_abort,
72 pth_raise,
73 pth_join,
74 pth_exit.
75
76 =item B<Utilities>
77
78 pth_fdmode,
79 pth_time,
80 pth_timeout,
81 pth_sfiodisc.
82
83 =item B<Cancellation Management>
84
85 pth_cancel_point,
86 pth_cancel_state.
87
88 =item B<Event Handling>
89
90 pth_event,
91 pth_event_typeof,
92 pth_event_extract,
93 pth_event_concat,
94 pth_event_isolate,
95 pth_event_walk,
96 pth_event_status,
97 pth_event_free.
98
99 =item B<Key-Based Storage>
100
101 pth_key_create,
102 pth_key_delete,
103 pth_key_setdata,
104 pth_key_getdata.
105
106 =item B<Message Port Communication>
107
108 pth_msgport_create,
109 pth_msgport_destroy,
110 pth_msgport_find,
111 pth_msgport_pending,
112 pth_msgport_put,
113 pth_msgport_get,
114 pth_msgport_reply.
115
116 =item B<Thread Cleanups>
117
118 pth_cleanup_push,
119 pth_cleanup_pop.
120
121 =item B<Process Forking>
122
123 pth_atfork_push,
124 pth_atfork_pop,
125 pth_fork.
126
127 =item B<Synchronization>
128
129 pth_mutex_init,
130 pth_mutex_acquire,
131 pth_mutex_release,
132 pth_rwlock_init,
133 pth_rwlock_acquire,
134 pth_rwlock_release,
135 pth_cond_init,
136 pth_cond_await,
137 pth_cond_notify,
138 pth_barrier_init,
139 pth_barrier_reach.
140
141 =item B<User-Space Context>
142
143 pth_uctx_create,
144 pth_uctx_make,
145 pth_uctx_switch,
146 pth_uctx_destroy.
147
148 =item B<Generalized POSIX Replacement API>
149
150 pth_sigwait_ev,
151 pth_accept_ev,
152 pth_connect_ev,
153 pth_select_ev,
154 pth_poll_ev,
155 pth_read_ev,
156 pth_readv_ev,
157 pth_write_ev,
158 pth_writev_ev,
159 pth_recv_ev,
160 pth_recvfrom_ev,
161 pth_send_ev,
162 pth_sendto_ev.
163
164 =item B<Standard POSIX Replacement API>
165
166 pth_nanosleep,
167 pth_usleep,
168 pth_sleep,
169 pth_waitpid,
170 pth_system,
171 pth_sigmask,
172 pth_sigwait,
173 pth_accept,
174 pth_connect,
175 pth_select,
176 pth_pselect,
177 pth_poll,
178 pth_read,
179 pth_readv,
180 pth_write,
181 pth_writev,
182 pth_pread,
183 pth_pwrite,
184 pth_recv,
185 pth_recvfrom,
186 pth_send,
187 pth_sendto.
188
189 =back
190
191 =head1 DESCRIPTION
192
193   ____  _   _
194  |  _ \| |_| |__
195  | |_) | __| '_ \         ``Only those who attempt
196  |  __/| |_| | | |          the absurd can achieve
197  |_|    \__|_| |_|          the impossible.''
198
199 B<Pth> is a very portable POSIX/ANSI-C based library for Unix platforms which
200 provides non-preemptive priority-based scheduling for multiple threads of
201 execution (aka `multithreading') inside event-driven applications. All threads
202 run in the same address space of the application process, but each thread has
203 its own individual program counter, run-time stack, signal mask and C<errno>
204 variable.
205
206 The thread scheduling itself is done in a cooperative way, i.e., the threads
207 are managed and dispatched by a priority- and event-driven non-preemptive
208 scheduler. The intention is that this way both better portability and run-time
209 performance is achieved than with preemptive scheduling. The event facility
210 allows threads to wait until various types of internal and external events
211 occur, including pending I/O on file descriptors, asynchronous signals,
212 elapsed timers, pending I/O on message ports, thread and process termination,
213 and even results of customized callback functions.
214
215 B<Pth> also provides an optional emulation API for POSIX.1c threads
216 (`Pthreads') which can be used for backward compatibility to existing
217 multithreaded applications. See B<Pth>'s pthread(3) manual page for
218 details.
219
220 =head2 Threading Background
221
222 When programming event-driven applications, usually servers, lots of
223 regular jobs and one-shot requests have to be processed in parallel.
224 To efficiently simulate this parallel processing on uniprocessor
225 machines, we use `multitasking' -- that is, we have the application
226 ask the operating system to spawn multiple instances of itself. On
227 Unix, typically the kernel implements multitasking in a preemptive and
228 priority-based way through heavy-weight processes spawned with fork(2).
229 These processes usually do I<not> share a common address space. Instead
230 they are clearly separated from each other, and are created by direct
231 cloning a process address space (although modern kernels use memory
232 segment mapping and copy-on-write semantics to avoid unnecessary copying
233 of physical memory).
234
235 The drawbacks are obvious: Sharing data between the processes is
236 complicated, and can usually only be done efficiently through shared
237 memory (but which itself is not very portable). Synchronization is
238 complicated because of the preemptive nature of the Unix scheduler
239 (one has to use I<atomic> locks, etc). The machine's resources can be
240 exhausted very quickly when the server application has to serve too many
241 long-running requests (heavy-weight processes cost memory). And when
242 each request spawns a sub-process to handle it, the server performance
243 and responsiveness is horrible (heavy-weight processes cost time to
244 spawn). Finally, the server application doesn't scale very well with the
245 load because of these resource problems. In practice, lots of tricks
246 are usually used to overcome these problems - ranging from pre-forked
247 sub-process pools to semi-serialized processing, etc.
248
249 One of the most elegant ways to solve these resource- and data-sharing
250 problems is to have multiple I<light-weight> threads of execution
251 inside a single (heavy-weight) process, i.e., to use I<multithreading>.
252 Those I<threads> usually improve responsiveness and performance of the
253 application, often improve and simplify the internal program structure,
254 and most important, require less system resources than heavy-weight
255 processes. Threads are neither the optimal run-time facility for all
256 types of applications, nor can all applications benefit from them. But
257 at least event-driven server applications usually benefit greatly from
258 using threads.
259
260 =head2 The World of Threading
261
262 Even though lots of documents exists which describe and define the world
263 of threading, to understand B<Pth>, you need only basic knowledge about
264 threading. The following definitions of thread-related terms should at
265 least help you understand thread programming enough to allow you to use
266 B<Pth>.
267
268 =over 2
269
270 =item B<o> B<process> vs. B<thread>
271
272 A process on Unix systems consists of at least the following fundamental
273 ingredients: I<virtual memory table>, I<program code>, I<program
274 counter>, I<heap memory>, I<stack memory>, I<stack pointer>, I<file
275 descriptor set>, I<signal table>. On every process switch, the kernel
276 saves and restores these ingredients for the individual processes. On
277 the other hand, a thread consists of only a private program counter,
278 stack memory, stack pointer and signal table. All other ingredients, in
279 particular the virtual memory, it shares with the other threads of the
280 same process.
281
282 =item B<o> B<kernel-space> vs. B<user-space> threading
283
284 Threads on a Unix platform traditionally can be implemented either
285 inside kernel-space or user-space. When threads are implemented by the
286 kernel, the thread context switches are performed by the kernel without
287 the application's knowledge. Similarly, when threads are implemented in
288 user-space, the thread context switches are performed by an application
289 library, without the kernel's knowledge. There also are hybrid threading
290 approaches where, typically, a user-space library binds one or more
291 user-space threads to one or more kernel-space threads (there usually
292 called light-weight processes - or in short LWPs).
293
294 User-space threads are usually more portable and can perform faster
295 and cheaper context switches (for instance via swapcontext(2) or
296 setjmp(3)/longjmp(3)) than kernel based threads. On the other hand,
297 kernel-space threads can take advantage of multiprocessor machines and
298 don't have any inherent I/O blocking problems. Kernel-space threads are
299 usually scheduled in preemptive way side-by-side with the underlying
300 processes. User-space threads on the other hand use either preemptive or
301 non-preemptive scheduling.
302
303 =item B<o> B<preemptive> vs. B<non-preemptive> thread scheduling
304
305 In preemptive scheduling, the scheduler lets a thread execute until a
306 blocking situation occurs (usually a function call which would block)
307 or the assigned timeslice elapses. Then it detracts control from the
308 thread without a chance for the thread to object. This is usually
309 realized by interrupting the thread through a hardware interrupt
310 signal (for kernel-space threads) or a software interrupt signal (for
311 user-space threads), like C<SIGALRM> or C<SIGVTALRM>. In non-preemptive
312 scheduling, once a thread received control from the scheduler it keeps
313 it until either a blocking situation occurs (again a function call which
314 would block and instead switches back to the scheduler) or the thread
315 explicitly yields control back to the scheduler in a cooperative way.
316
317 =item B<o> B<concurrency> vs. B<parallelism>
318
319 Concurrency exists when at least two threads are I<in progress> at the
320 same time. Parallelism arises when at least two threads are I<executing>
321 simultaneously. Real parallelism can be only achieved on multiprocessor
322 machines, of course. But one also usually speaks of parallelism or
323 I<high concurrency> in the context of preemptive thread scheduling
324 and of I<low concurrency> in the context of non-preemptive thread
325 scheduling.
326
327 =item B<o> B<responsiveness>
328
329 The responsiveness of a system can be described by the user visible
330 delay until the system responses to an external request. When this delay
331 is small enough and the user doesn't recognize a noticeable delay,
332 the responsiveness of the system is considered good. When the user
333 recognizes or is even annoyed by the delay, the responsiveness of the
334 system is considered bad.
335
336 =item B<o> B<reentrant>, B<thread-safe> and B<asynchronous-safe> functions
337
338 A reentrant function is one that behaves correctly if it is called
339 simultaneously by several threads and then also executes simultaneously.
340 Functions that access global state, such as memory or files, of course,
341 need to be carefully designed in order to be reentrant. Two traditional
342 approaches to solve these problems are caller-supplied states and
343 thread-specific data.
344
345 Thread-safety is the avoidance of I<data races>, i.e., situations
346 in which data is set to either correct or incorrect value depending
347 upon the (unpredictable) order in which multiple threads access and
348 modify the data. So a function is thread-safe when it still behaves
349 semantically correct when called simultaneously by several threads (it
350 is not required that the functions also execute simultaneously). The
351 traditional approach to achieve thread-safety is to wrap a function body
352 with an internal mutual exclusion lock (aka `mutex'). As you should
353 recognize, reentrant is a stronger attribute than thread-safe, because
354 it is harder to achieve and results especially in no run-time contention
355 between threads. So, a reentrant function is always thread-safe, but not
356 vice versa.
357
358 Additionally there is a related attribute for functions named
359 asynchronous-safe, which comes into play in conjunction with signal
360 handlers. This is very related to the problem of reentrant functions. An
361 asynchronous-safe function is one that can be called safe and without
362 side-effects from within a signal handler context. Usually very few
363 functions are of this type, because an application is very restricted in
364 what it can perform from within a signal handler (especially what system
365 functions it is allowed to call). The reason mainly is, because only a
366 few system functions are officially declared by POSIX as guaranteed to
367 be asynchronous-safe. Asynchronous-safe functions usually have to be
368 already reentrant.
369
370 =back
371
372 =head2 User-Space Threads
373
374 User-space threads can be implemented in various way. The two
375 traditional approaches are:
376
377 =over 3
378
379 =item B<1.>
380
381 B<Matrix-based explicit dispatching between small units of execution:>
382
383 Here the global procedures of the application are split into small
384 execution units (each is required to not run for more than a few
385 milliseconds) and those units are implemented by separate functions.
386 Then a global matrix is defined which describes the execution (and
387 perhaps even dependency) order of these functions. The main server
388 procedure then just dispatches between these units by calling one
389 function after each other controlled by this matrix. The threads are
390 created by more than one jump-trail through this matrix and by switching
391 between these jump-trails controlled by corresponding occurred events.
392
393 This approach gives the best possible performance, because one can
394 fine-tune the threads of execution by adjusting the matrix, and the
395 scheduling is done explicitly by the application itself. It is also very
396 portable, because the matrix is just an ordinary data structure, and
397 functions are a standard feature of ANSI C.
398
399 The disadvantage of this approach is that it is complicated to write
400 large applications with this approach, because in those applications
401 one quickly gets hundreds(!) of execution units and the control flow
402 inside such an application is very hard to understand (because it is
403 interrupted by function borders and one always has to remember the
404 global dispatching matrix to follow it). Additionally, all threads
405 operate on the same execution stack. Although this saves memory, it is
406 often nasty, because one cannot switch between threads in the middle of
407 a function. Thus the scheduling borders are the function borders.
408
409 =item B<2.>
410
411 B<Context-based implicit scheduling between threads of execution:>
412
413 Here the idea is that one programs the application as with forked
414 processes, i.e., one spawns a thread of execution and this runs from the
415 begin to the end without an interrupted control flow. But the control
416 flow can be still interrupted - even in the middle of a function.
417 Actually in a preemptive way, similar to what the kernel does for the
418 heavy-weight processes, i.e., every few milliseconds the user-space
419 scheduler switches between the threads of execution. But the thread
420 itself doesn't recognize this and usually (except for synchronization
421 issues) doesn't have to care about this.
422
423 The advantage of this approach is that it's very easy to program,
424 because the control flow and context of a thread directly follows
425 a procedure without forced interrupts through function borders.
426 Additionally, the programming is very similar to a traditional and well
427 understood fork(2) based approach.
428
429 The disadvantage is that although the general performance is increased,
430 compared to using approaches based on heavy-weight processes, it is decreased
431 compared to the matrix-approach above. Because the implicit preemptive
432 scheduling does usually a lot more context switches (every user-space context
433 switch costs some overhead even when it is a lot cheaper than a kernel-level
434 context switch) than the explicit cooperative/non-preemptive scheduling.
435 Finally, there is no really portable POSIX/ANSI-C based way to implement
436 user-space preemptive threading. Either the platform already has threads,
437 or one has to hope that some semi-portable package exists for it. And
438 even those semi-portable packages usually have to deal with assembler
439 code and other nasty internals and are not easy to port to forthcoming
440 platforms.
441
442 =back
443
444 So, in short: the matrix-dispatching approach is portable and fast, but
445 nasty to program. The thread scheduling approach is easy to program,
446 but suffers from synchronization and portability problems caused by its
447 preemptive nature.
448
449 =head2 The Compromise of Pth
450
451 But why not combine the good aspects of both approaches while avoiding
452 their bad aspects? That's the goal of B<Pth>. B<Pth> implements
453 easy-to-program threads of execution, but avoids the problems of
454 preemptive scheduling by using non-preemptive scheduling instead.
455
456 This sounds like, and is, a useful approach. Nevertheless, one has to
457 keep the implications of non-preemptive thread scheduling in mind when
458 working with B<Pth>. The following list summarizes a few essential
459 points:
460
461 =over 2
462
463 =item B<o>
464
465 B<Pth provides maximum portability, but NOT the fanciest features>.
466
467 This is, because it uses a nifty and portable POSIX/ANSI-C approach for
468 thread creation (and this way doesn't require any platform dependent
469 assembler hacks) and schedules the threads in non-preemptive way (which
470 doesn't require unportable facilities like C<SIGVTALRM>). On the other
471 hand, this way not all fancy threading features can be implemented.
472 Nevertheless the available facilities are enough to provide a robust and
473 full-featured threading system.
474
475 =item B<o>
476
477 B<Pth increases the responsiveness and concurrency of an event-driven
478 application, but NOT the concurrency of number-crunching applications>.
479
480 The reason is the non-preemptive scheduling. Number-crunching
481 applications usually require preemptive scheduling to achieve
482 concurrency because of their long CPU bursts. For them, non-preemptive
483 scheduling (even together with explicit yielding) provides only the old
484 concept of `coroutines'. On the other hand, event driven applications
485 benefit greatly from non-preemptive scheduling. They have only short
486 CPU bursts and lots of events to wait on, and this way run faster under
487 non-preemptive scheduling because no unnecessary context switching
488 occurs, as it is the case for preemptive scheduling. That's why B<Pth>
489 is mainly intended for server type applications, although there is no
490 technical restriction.
491
492 =item B<o>
493
494 B<Pth requires thread-safe functions, but NOT reentrant functions>.
495
496 This nice fact exists again because of the nature of non-preemptive
497 scheduling, where a function isn't interrupted and this way cannot be
498 reentered before it returned. This is a great portability benefit,
499 because thread-safety can be achieved more easily than reentrance
500 possibility. Especially this means that under B<Pth> more existing
501 third-party libraries can be used without side-effects than it's the case
502 for other threading systems.
503
504 =item B<o>
505
506 B<Pth doesn't require any kernel support, but can NOT
507 benefit from multiprocessor machines>.
508
509 This means that B<Pth> runs on almost all Unix kernels, because the
510 kernel does not need to be aware of the B<Pth> threads (because they
511 are implemented entirely in user-space). On the other hand, it cannot
512 benefit from the existence of multiprocessors, because for this, kernel
513 support would be needed. In practice, this is no problem, because
514 multiprocessor systems are rare, and portability is almost more
515 important than highest concurrency.
516
517 =back
518
519 =head2 The life cycle of a thread
520
521 To understand the B<Pth> Application Programming Interface (API), it
522 helps to first understand the life cycle of a thread in the B<Pth>
523 threading system. It can be illustrated with the following directed
524 graph:
525
526              NEW
527               |
528               V
529       +---> READY ---+
530       |       ^      |
531       |       |      V
532    WAITING <--+-- RUNNING
533                      |
534       :              V
535    SUSPENDED       DEAD
536
537 When a new thread is created, it is moved into the B<NEW> queue of the
538 scheduler. On the next dispatching for this thread, the scheduler picks
539 it up from there and moves it to the B<READY> queue. This is a queue
540 containing all threads which want to perform a CPU burst. There they are
541 queued in priority order. On each dispatching step, the scheduler always
542 removes the thread with the highest priority only. It then increases the
543 priority of all remaining threads by 1, to prevent them from `starving'.
544
545 The thread which was removed from the B<READY> queue is the new
546 B<RUNNING> thread (there is always just one B<RUNNING> thread, of
547 course). The B<RUNNING> thread is assigned execution control. After
548 this thread yields execution (either explicitly by yielding execution
549 or implicitly by calling a function which would block) there are three
550 possibilities: Either it has terminated, then it is moved to the B<DEAD>
551 queue, or it has events on which it wants to wait, then it is moved into
552 the B<WAITING> queue. Else it is assumed it wants to perform more CPU
553 bursts and immediately enters the B<READY> queue again.
554
555 Before the next thread is taken out of the B<READY> queue, the
556 B<WAITING> queue is checked for pending events. If one or more events
557 occurred, the threads that are waiting on them are immediately moved to
558 the B<READY> queue.
559
560 The purpose of the B<NEW> queue has to do with the fact that in B<Pth>
561 a thread never directly switches to another thread. A thread always
562 yields execution to the scheduler and the scheduler dispatches to the
563 next thread. So a freshly spawned thread has to be kept somewhere until
564 the scheduler gets a chance to pick it up for scheduling. That is
565 what the B<NEW> queue is for.
566
567 The purpose of the B<DEAD> queue is to support thread joining. When a
568 thread is marked to be unjoinable, it is directly kicked out of the
569 system after it terminated. But when it is joinable, it enters the
570 B<DEAD> queue. There it remains until another thread joins it.
571
572 Finally, there is a special separated queue named B<SUSPENDED>, to where
573 threads can be manually moved from the B<NEW>, B<READY> or B<WAITING>
574 queues by the application. The purpose of this special queue is to
575 temporarily absorb suspended threads until they are again resumed by
576 the application. Suspended threads do not cost scheduling or event
577 handling resources, because they are temporarily completely out of the
578 scheduler's scope. If a thread is resumed, it is moved back to the queue
579 from where it originally came and this way again enters the schedulers
580 scope.
581
582 =head1 APPLICATION PROGRAMMING INTERFACE (API)
583
584 In the following the B<Pth> I<Application Programming Interface> (API)
585 is discussed in detail. With the knowledge given above, it should now
586 be easy to understand how to program threads with this API. In good
587 Unix tradition, B<Pth> functions use special return values (C<NULL>
588 in pointer context, C<FALSE> in boolean context and C<-1> in integer
589 context) to indicate an error condition and set (or pass through) the
590 C<errno> system variable to pass more details about the error to the
591 caller.
592
593 =head2 Global Library Management
594
595 The following functions act on the library as a whole.  They are used to
596 initialize and shutdown the scheduler and fetch information from it.
597
598 =over 4
599
600 =item int B<pth_init>(void);
601
602 This initializes the B<Pth> library. It has to be the first B<Pth> API
603 function call in an application, and is mandatory. It's usually done at
604 the begin of the main() function of the application. This implicitly
605 spawns the internal scheduler thread and transforms the single execution
606 unit of the current process into a thread (the `main' thread). It
607 returns C<TRUE> on success and C<FALSE> on error.
608
609 =item int B<pth_kill>(void);
610
611 This kills the B<Pth> library. It should be the last B<Pth> API function call
612 in an application, but is not really required. It's usually done at the end of
613 the main function of the application. At least, it has to be called from within
614 the main thread. It implicitly kills all threads and transforms back the
615 calling thread into the single execution unit of the underlying process.  The
616 usual way to terminate a B<Pth> application is either a simple
617 `C<pth_exit(0);>' in the main thread (which waits for all other threads to
618 terminate, kills the threading system and then terminates the process) or a
619 `C<pth_kill(); exit(0)>' (which immediately kills the threading system and
620 terminates the process). The pth_kill() return immediately with a return
621 code of C<FALSE> if it is not called from within the main thread. Else it
622 kills the threading system and returns C<TRUE>.
623
624 =item long B<pth_ctrl>(unsigned long I<query>, ...);
625
626 This is a generalized query/control function for the B<Pth> library.  The
627 argument I<query> is a bitmask formed out of one or more C<PTH_CTRL_>I<XXXX>
628 queries. Currently the following queries are supported:
629
630 =over 4
631
632 =item C<PTH_CTRL_GETTHREADS>
633
634 This returns the total number of threads currently in existence.  This query
635 actually is formed out of the combination of queries for threads in a
636 particular state, i.e., the C<PTH_CTRL_GETTHREADS> query is equal to the
637 OR-combination of all the following specialized queries:
638
639 C<PTH_CTRL_GETTHREADS_NEW> for the number of threads in the
640 new queue (threads created via pth_spawn(3) but still not
641 scheduled once), C<PTH_CTRL_GETTHREADS_READY> for the number of
642 threads in the ready queue (threads who want to do CPU bursts),
643 C<PTH_CTRL_GETTHREADS_RUNNING> for the number of running threads
644 (always just one thread!), C<PTH_CTRL_GETTHREADS_WAITING> for
645 the number of threads in the waiting queue (threads waiting for
646 events), C<PTH_CTRL_GETTHREADS_SUSPENDED> for the number of
647 threads in the suspended queue (threads waiting to be resumed) and
648 C<PTH_CTRL_GETTHREADS_DEAD> for the number of threads in the new queue
649 (terminated threads waiting for a join).
650
651 =item C<PTH_CTRL_GETAVLOAD>
652
653 This requires a second argument of type `C<float *>' (pointer to a floating
654 point variable).  It stores a floating point value describing the exponential
655 averaged load of the scheduler in this variable. The load is a function from
656 the number of threads in the ready queue of the schedulers dispatching unit.
657 So a load around 1.0 means there is only one ready thread (the standard
658 situation when the application has no high load). A higher load value means
659 there a more threads ready who want to do CPU bursts. The average load value
660 updates once per second only. The return value for this query is always 0.
661
662 =item C<PTH_CTRL_GETPRIO>
663
664 This requires a second argument of type `C<pth_t>' which identifies a
665 thread.  It returns the priority (ranging from C<PTH_PRIO_MIN> to
666 C<PTH_PRIO_MAX>) of the given thread.
667
668 =item C<PTH_CTRL_GETNAME>
669
670 This requires a second argument of type `C<pth_t>' which identifies a
671 thread. It returns the name of the given thread, i.e., the return value of
672 pth_ctrl(3) should be casted to a `C<char *>'.
673
674 =item C<PTH_CTRL_DUMPSTATE>
675
676 This requires a second argument of type `C<FILE *>' to which a summary
677 of the internal B<Pth> library state is written to. The main information
678 which is currently written out is the current state of the thread pool.
679
680 =item C<PTH_CTRL_FAVOURNEW>
681
682 This requires a second argument of type `C<int>' which specified whether
683 the B<GNU Pth> scheduler favours new threads on startup, i.e., whether
684 they are moved from the new queue to the top (argument is C<TRUE>) or
685 middle (argument is C<FALSE>) of the ready queue. The default is to
686 favour new threads to make sure they do not starve already at startup,
687 although this slightly violates the strict priority based scheduling.
688
689 =back
690
691 The function returns C<-1> on error.
692
693 =item long B<pth_version>(void);
694
695 This function returns a hex-value `0xI<V>I<RR>I<T>I<LL>' which describes the
696 current B<Pth> library version. I<V> is the version, I<RR> the revisions,
697 I<LL> the level and I<T> the type of the level (alphalevel=0, betalevel=1,
698 patchlevel=2, etc). For instance B<Pth> version 1.0b1 is encoded as 0x100101.
699 The reason for this unusual mapping is that this way the version number is
700 steadily I<increasing>. The same value is also available under compile time as
701 C<PTH_VERSION>.
702
703 =back
704
705 =head2 Thread Attribute Handling
706
707 Attribute objects are used in B<Pth> for two things: First stand-alone/unbound
708 attribute objects are used to store attributes for to be spawned threads.
709 Bounded attribute objects are used to modify attributes of already existing
710 threads. The following attribute fields exists in attribute objects:
711
712 =over 4
713
714 =item C<PTH_ATTR_PRIO> (read-write) [C<int>]
715
716 Thread Priority between C<PTH_PRIO_MIN> and C<PTH_PRIO_MAX>.
717 The default is C<PTH_PRIO_STD>.
718
719 =item C<PTH_ATTR_NAME> (read-write) [C<char *>]
720
721 Name of thread (up to 40 characters are stored only), mainly for debugging
722 purposes.
723
724 =item C<PTH_ATTR_DISPATCHES> (read-write) [C<int>]
725
726 In bounded attribute objects, this field is incremented every time the
727 context is switched to the associated thread.
728
729 =item C<PTH_ATTR_JOINABLE> (read-write> [C<int>]
730
731 The thread detachment type, C<TRUE> indicates a joinable thread,
732 C<FALSE> indicates a detached thread. When a thread is detached,
733 after termination it is immediately kicked out of the system instead of
734 inserted into the dead queue.
735
736 =item C<PTH_ATTR_CANCEL_STATE> (read-write) [C<unsigned int>]
737
738 The thread cancellation state, i.e., a combination of C<PTH_CANCEL_ENABLE> or
739 C<PTH_CANCEL_DISABLE> and C<PTH_CANCEL_DEFERRED> or
740 C<PTH_CANCEL_ASYNCHRONOUS>.
741
742 =item C<PTH_ATTR_STACK_SIZE> (read-write) [C<unsigned int>]
743
744 The thread stack size in bytes. Use lower values than 64 KB with great care!
745
746 =item C<PTH_ATTR_STACK_ADDR> (read-write) [C<char *>]
747
748 A pointer to the lower address of a chunk of malloc(3)'ed memory for the
749 stack.
750
751 =item C<PTH_ATTR_TIME_SPAWN> (read-only) [C<pth_time_t>]
752
753 The time when the thread was spawned.
754 This can be queried only when the attribute object is bound to a thread.
755
756 =item C<PTH_ATTR_TIME_LAST> (read-only) [C<pth_time_t>]
757
758 The time when the thread was last dispatched.
759 This can be queried only when the attribute object is bound to a thread.
760
761 =item C<PTH_ATTR_TIME_RAN> (read-only) [C<pth_time_t>]
762
763 The total time the thread was running.
764 This can be queried only when the attribute object is bound to a thread.
765
766 =item C<PTH_ATTR_START_FUNC> (read-only) [C<void *(*)(void *)>]
767
768 The thread start function.
769 This can be queried only when the attribute object is bound to a thread.
770
771 =item C<PTH_ATTR_START_ARG> (read-only) [C<void *>]
772
773 The thread start argument.
774 This can be queried only when the attribute object is bound to a thread.
775
776 =item C<PTH_ATTR_STATE> (read-only) [C<pth_state_t>]
777
778 The scheduling state of the thread, i.e., either C<PTH_STATE_NEW>,
779 C<PTH_STATE_READY>, C<PTH_STATE_WAITING>, or C<PTH_STATE_DEAD>
780 This can be queried only when the attribute object is bound to a thread.
781
782 =item C<PTH_ATTR_EVENTS> (read-only) [C<pth_event_t>]
783
784 The event ring the thread is waiting for.
785 This can be queried only when the attribute object is bound to a thread.
786
787 =item C<PTH_ATTR_BOUND> (read-only) [C<int>]
788
789 Whether the attribute object is bound (C<TRUE>) to a thread or not (C<FALSE>).
790
791 =back
792
793 The following API functions can be used to handle the attribute objects:
794
795 =over 4
796
797 =item pth_attr_t B<pth_attr_of>(pth_t I<tid>);
798
799 This returns a new attribute object I<bound> to thread I<tid>.  Any queries on
800 this object directly fetch attributes from I<tid>. And attribute modifications
801 directly change I<tid>. Use such attribute objects to modify existing threads.
802
803 =item pth_attr_t B<pth_attr_new>(void);
804
805 This returns a new I<unbound> attribute object. An implicit pth_attr_init() is
806 done on it. Any queries on this object just fetch stored attributes from it.
807 And attribute modifications just change the stored attributes.  Use such
808 attribute objects to pre-configure attributes for to be spawned threads.
809
810 =item int B<pth_attr_init>(pth_attr_t I<attr>);
811
812 This initializes an attribute object I<attr> to the default values:
813 C<PTH_ATTR_PRIO> := C<PTH_PRIO_STD>, C<PTH_ATTR_NAME> := `C<unknown>',
814 C<PTH_ATTR_DISPATCHES> := C<0>, C<PTH_ATTR_JOINABLE> := C<TRUE>,
815 C<PTH_ATTR_CANCELSTATE> := C<PTH_CANCEL_DEFAULT>,
816 C<PTH_ATTR_STACK_SIZE> := 64*1024 and
817 C<PTH_ATTR_STACK_ADDR> := C<NULL>. All other C<PTH_ATTR_*> attributes are
818 read-only attributes and don't receive default values in I<attr>, because they
819 exists only for bounded attribute objects.
820
821 =item int B<pth_attr_set>(pth_attr_t I<attr>, int I<field>, ...);
822
823 This sets the attribute field I<field> in I<attr> to a value
824 specified as an additional argument on the variable argument
825 list. The following attribute I<fields> and argument pairs can
826 be used:
827
828  PTH_ATTR_PRIO           int
829  PTH_ATTR_NAME           char *
830  PTH_ATTR_DISPATCHES     int
831  PTH_ATTR_JOINABLE       int
832  PTH_ATTR_CANCEL_STATE   unsigned int
833  PTH_ATTR_STACK_SIZE     unsigned int
834  PTH_ATTR_STACK_ADDR     char *
835
836 =item int B<pth_attr_get>(pth_attr_t I<attr>, int I<field>, ...);
837
838 This retrieves the attribute field I<field> in I<attr> and stores its
839 value in the variable specified through a pointer in an additional
840 argument on the variable argument list. The following I<fields> and
841 argument pairs can be used:
842
843  PTH_ATTR_PRIO           int *
844  PTH_ATTR_NAME           char **
845  PTH_ATTR_DISPATCHES     int *
846  PTH_ATTR_JOINABLE       int *
847  PTH_ATTR_CANCEL_STATE   unsigned int *
848  PTH_ATTR_STACK_SIZE     unsigned int *
849  PTH_ATTR_STACK_ADDR     char **
850  PTH_ATTR_TIME_SPAWN     pth_time_t *
851  PTH_ATTR_TIME_LAST      pth_time_t *
852  PTH_ATTR_TIME_RAN       pth_time_t *
853  PTH_ATTR_START_FUNC     void *(**)(void *)
854  PTH_ATTR_START_ARG      void **
855  PTH_ATTR_STATE          pth_state_t *
856  PTH_ATTR_EVENTS         pth_event_t *
857  PTH_ATTR_BOUND          int *
858
859 =item int B<pth_attr_destroy>(pth_attr_t I<attr>);
860
861 This destroys a attribute object I<attr>. After this I<attr> is no
862 longer a valid attribute object.
863
864 =back
865
866 =head2 Thread Control
867
868 The following functions control the threading itself and make up the main API
869 of the B<Pth> library.
870
871 =over 4
872
873 =item pth_t B<pth_spawn>(pth_attr_t I<attr>, void *(*I<entry>)(void *), void *I<arg>);
874
875 This spawns a new thread with the attributes given in I<attr> (or
876 C<PTH_ATTR_DEFAULT> for default attributes - which means that thread priority,
877 joinability and cancel state are inherited from the current thread) with the
878 starting point at routine I<entry>; the dispatch count is not inherited from
879 the current thread if I<attr> is not specified - rather, it is initialized
880 to zero.  This entry routine is called as `pth_exit(I<entry>(I<arg>))' inside
881 the new thread unit, i.e., I<entry>'s return value is fed to an implicit
882 pth_exit(3). So the thread can also exit by just returning. Nevertheless
883 the thread can also exit explicitly at any time by calling pth_exit(3). But
884 keep in mind that calling the POSIX function exit(3) still terminates the
885 complete process and not just the current thread.
886
887 There is no B<Pth>-internal limit on the number of threads one can spawn,
888 except the limit implied by the available virtual memory. B<Pth> internally
889 keeps track of thread in dynamic data structures. The function returns
890 C<NULL> on error.
891
892 =item int B<pth_once>(pth_once_t *I<ctrlvar>, void (*I<func>)(void *), void *I<arg>);
893
894 This is a convenience function which uses a control variable of type
895 C<pth_once_t> to make sure a constructor function I<func> is called only once
896 as `I<func>(I<arg>)' in the system. In other words: Only the first call to
897 pth_once(3) by any thread in the system succeeds. The variable referenced via
898 I<ctrlvar> should be declared as `C<pth_once_t> I<variable-name> =
899 C<PTH_ONCE_INIT>;' before calling this function.
900
901 =item pth_t B<pth_self>(void);
902
903 This just returns the unique thread handle of the currently running thread.
904 This handle itself has to be treated as an opaque entity by the application.
905 It's usually used as an argument to other functions who require an argument of
906 type C<pth_t>.
907
908 =item int B<pth_suspend>(pth_t I<tid>);
909
910 This suspends a thread I<tid> until it is manually resumed again via
911 pth_resume(3). For this, the thread is moved to the B<SUSPENDED> queue
912 and this way is completely out of the scheduler's event handling and
913 thread dispatching scope. Suspending the current thread is not allowed.
914 The function returns C<TRUE> on success and C<FALSE> on errors.
915
916 =item int B<pth_resume>(pth_t I<tid>);
917
918 This function resumes a previously suspended thread I<tid>, i.e. I<tid>
919 has to stay on the B<SUSPENDED> queue. The thread is moved to the
920 B<NEW>, B<READY> or B<WAITING> queue (dependent on what its state was
921 when the pth_suspend(3) call were made) and this way again enters the
922 event handling and thread dispatching scope of the scheduler. The
923 function returns C<TRUE> on success and C<FALSE> on errors.
924
925 =item int B<pth_raise>(pth_t I<tid>, int I<sig>)
926
927 This function raises a signal for delivery to thread I<tid> only.  When one
928 just raises a signal via raise(3) or kill(2), its delivered to an arbitrary
929 thread which has this signal not blocked.  With pth_raise(3) one can send a
930 signal to a thread and its guarantees that only this thread gets the signal
931 delivered. But keep in mind that nevertheless the signals I<action> is still
932 configured I<process>-wide.  When I<sig> is 0 plain thread checking is
933 performed, i.e., `C<pth_raise(tid, 0)>' returns C<TRUE> when thread I<tid>
934 still exists in the B<PTH> system but doesn't send any signal to it.
935
936 =item int B<pth_yield>(pth_t I<tid>);
937
938 This explicitly yields back the execution control to the scheduler thread.
939 Usually the execution is implicitly transferred back to the scheduler when a
940 thread waits for an event. But when a thread has to do larger CPU bursts, it
941 can be reasonable to interrupt it explicitly by doing a few pth_yield(3) calls
942 to give other threads a chance to execute, too.  This obviously is the
943 cooperating part of B<Pth>.  A thread I<has not> to yield execution, of
944 course. But when you want to program a server application with good response
945 times the threads should be cooperative, i.e., when they should split their CPU
946 bursts into smaller units with this call.
947
948 Usually one specifies I<tid> as C<NULL> to indicate to the scheduler that it
949 can freely decide which thread to dispatch next.  But if one wants to indicate
950 to the scheduler that a particular thread should be favored on the next
951 dispatching step, one can specify this thread explicitly. This allows the
952 usage of the old concept of I<coroutines> where a thread/routine switches to a
953 particular cooperating thread. If I<tid> is not C<NULL> and points to a I<new>
954 or I<ready> thread, it is guaranteed that this thread receives execution
955 control on the next dispatching step. If I<tid> is in a different state (that
956 is, not in C<PTH_STATE_NEW> or C<PTH_STATE_READY>) an error is reported.
957
958 The function usually returns C<TRUE> for success and only C<FALSE> (with
959 C<errno> set to C<EINVAL>) if I<tid> specified an invalid or still not
960 new or ready thread.
961
962 =item int B<pth_nap>(pth_time_t I<naptime>);
963
964 This functions suspends the execution of the current thread until I<naptime>
965 is elapsed. I<naptime> is of type C<pth_time_t> and this way has theoretically
966 a resolution of one microsecond. In practice you should neither rely on this
967 nor that the thread is awakened exactly after I<naptime> has elapsed. It's
968 only guarantees that the thread will sleep at least I<naptime>. But because
969 of the non-preemptive nature of B<Pth> it can last longer (when another thread
970 kept the CPU for a long time). Additionally the resolution is dependent of the
971 implementation of timers by the operating system and these usually have only a
972 resolution of 10 microseconds or larger. But usually this isn't important for
973 an application unless it tries to use this facility for real time tasks.
974
975 =item int B<pth_wait>(pth_event_t I<ev>);
976
977 This is the link between the scheduler and the event facility (see below for
978 the various pth_event_xxx() functions). It's modeled like select(2), i.e., one
979 gives this function one or more events (in the event ring specified by I<ev>)
980 on which the current thread wants to wait. The scheduler awakes the
981 thread when one ore more of them occurred or failed after tagging
982 them as such. The I<ev> argument is a I<pointer> to an event ring
983 which isn't changed except for the tagging. pth_wait(3) returns the
984 number of occurred or failed events and the application can use
985 pth_event_status(3) to test which events occurred or failed.
986
987 =item int B<pth_cancel>(pth_t I<tid>);
988
989 This cancels a thread I<tid>. How the cancellation is done depends on the
990 cancellation state of I<tid> which the thread can configure itself. When its
991 state is C<PTH_CANCEL_DISABLE> a cancellation request is just made pending.
992 When it is C<PTH_CANCEL_ENABLE> it depends on the cancellation type what is
993 performed. When its C<PTH_CANCEL_DEFERRED> again the cancellation request is
994 just made pending. But when its C<PTH_CANCEL_ASYNCHRONOUS> the thread is
995 immediately canceled before pth_cancel(3) returns. The effect of a thread
996 cancellation is equal to implicitly forcing the thread to call
997 `C<pth_exit(PTH_CANCELED)>' at one of his cancellation points.  In B<Pth>
998 thread enter a cancellation point either explicitly via pth_cancel_point(3) or
999 implicitly by waiting for an event.
1000
1001 =item int B<pth_abort>(pth_t I<tid>);
1002
1003 This is the cruel way to cancel a thread I<tid>. When it's already dead and
1004 waits to be joined it just joins it (via `C<pth_join(>I<tid>C<, NULL)>') and
1005 this way kicks it out of the system.  Else it forces the thread to be not
1006 joinable and to allow asynchronous cancellation and then cancels it via
1007 `C<pth_cancel(>I<tid>C<)>'.
1008
1009 =item int B<pth_join>(pth_t I<tid>, void **I<value>);
1010
1011 This joins the current thread with the thread specified via I<tid>.
1012 It first suspends the current thread until the I<tid> thread has
1013 terminated. Then it is awakened and stores the value of I<tid>'s
1014 pth_exit(3) call into *I<value> (if I<value> and not C<NULL>) and
1015 returns to the caller. A thread can be joined only when it has the
1016 attribute C<PTH_ATTR_JOINABLE> set to C<TRUE> (the default). A thread
1017 can only be joined once, i.e., after the pth_join(3) call the thread
1018 I<tid> is completely removed from the system.
1019
1020 =item void B<pth_exit>(void *I<value>);
1021
1022 This terminates the current thread. Whether it's immediately removed
1023 from the system or inserted into the dead queue of the scheduler depends
1024 on its join type which was specified at spawning time. If it has the
1025 attribute C<PTH_ATTR_JOINABLE> set to C<FALSE>, it's immediately removed
1026 and I<value> is ignored. Else the thread is inserted into the dead queue
1027 and I<value> remembered for a subsequent pth_join(3) call by another
1028 thread.
1029
1030 =back
1031
1032 =head2 Utilities
1033
1034 Utility functions.
1035
1036 =over 4
1037
1038 =item int B<pth_fdmode>(int I<fd>, int I<mode>);
1039
1040 This switches the non-blocking mode flag on file descriptor I<fd>.  The
1041 argument I<mode> can be C<PTH_FDMODE_BLOCK> for switching I<fd> into blocking
1042 I/O mode, C<PTH_FDMODE_NONBLOCK> for switching I<fd> into non-blocking I/O
1043 mode or C<PTH_FDMODE_POLL> for just polling the current mode. The current mode
1044 is returned (either C<PTH_FDMODE_BLOCK> or C<PTH_FDMODE_NONBLOCK>) or
1045 C<PTH_FDMODE_ERROR> on error. Keep in mind that since B<Pth> 1.1 there is no
1046 longer a requirement to manually switch a file descriptor into non-blocking
1047 mode in order to use it. This is automatically done temporarily inside B<Pth>.
1048 Instead when you now switch a file descriptor explicitly into non-blocking
1049 mode, pth_read(3) or pth_write(3) will never block the current thread.
1050
1051 =item pth_time_t B<pth_time>(long I<sec>, long I<usec>);
1052
1053 This is a constructor for a C<pth_time_t> structure which is a convenient
1054 function to avoid temporary structure values. It returns a I<pth_time_t>
1055 structure which holds the absolute time value specified by I<sec> and I<usec>.
1056
1057 =item pth_time_t B<pth_timeout>(long I<sec>, long I<usec>);
1058
1059 This is a constructor for a C<pth_time_t> structure which is a convenient
1060 function to avoid temporary structure values.  It returns a I<pth_time_t>
1061 structure which holds the absolute time value calculated by adding I<sec> and
1062 I<usec> to the current time.
1063
1064 =item Sfdisc_t *B<pth_sfiodisc>(void);
1065
1066 This functions is always available, but only reasonably usable when B<Pth>
1067 was built with B<Sfio> support (C<--with-sfio> option) and C<PTH_EXT_SFIO> is
1068 then defined by C<pth.h>. It is useful for applications which want to use the
1069 comprehensive B<Sfio> I/O library with the B<Pth> threading library. Then this
1070 function can be used to get an B<Sfio> discipline structure (C<Sfdisc_t>)
1071 which can be pushed onto B<Sfio> streams (C<Sfio_t>) in order to let this
1072 stream use pth_read(3)/pth_write(2) instead of read(2)/write(2). The benefit
1073 is that this way I/O on the B<Sfio> stream does only block the current thread
1074 instead of the whole process. The application has to free(3) the C<Sfdisc_t>
1075 structure when it is no longer needed. The Sfio package can be found at
1076 http://www.research.att.com/sw/tools/sfio/.
1077
1078 =back
1079
1080 =head2 Cancellation Management
1081
1082 B<Pth> supports POSIX style thread cancellation via pth_cancel(3) and the
1083 following two related functions:
1084
1085 =over 4
1086
1087 =item void B<pth_cancel_state>(int I<newstate>, int *I<oldstate>);
1088
1089 This manages the cancellation state of the current thread.  When I<oldstate>
1090 is not C<NULL> the function stores the old cancellation state under the
1091 variable pointed to by I<oldstate>. When I<newstate> is not C<0> it sets the
1092 new cancellation state. I<oldstate> is created before I<newstate> is set.  A
1093 state is a combination of C<PTH_CANCEL_ENABLE> or C<PTH_CANCEL_DISABLE> and
1094 C<PTH_CANCEL_DEFERRED> or C<PTH_CANCEL_ASYNCHRONOUS>.
1095 C<PTH_CANCEL_ENABLE|PTH_CANCEL_DEFERRED> (or C<PTH_CANCEL_DEFAULT>) is the
1096 default state where cancellation is possible but only at cancellation points.
1097 Use C<PTH_CANCEL_DISABLE> to complete disable cancellation for a thread and
1098 C<PTH_CANCEL_ASYNCHRONOUS> for allowing asynchronous cancellations, i.e.,
1099 cancellations which can happen at any time.
1100
1101 =item void B<pth_cancel_point>(void);
1102
1103 This explicitly enter a cancellation point. When the current cancellation
1104 state is C<PTH_CANCEL_DISABLE> or no cancellation request is pending, this has
1105 no side-effect and returns immediately. Else it calls
1106 `C<pth_exit(PTH_CANCELED)>'.
1107
1108 =back
1109
1110 =head2 Event Handling
1111
1112 B<Pth> has a very flexible event facility which is linked into the scheduler
1113 through the pth_wait(3) function. The following functions provide the handling
1114 of event rings.
1115
1116 =over 4
1117
1118 =item pth_event_t B<pth_event>(unsigned long I<spec>, ...);
1119
1120 This creates a new event ring consisting of a single initial event.  The type
1121 of the generated event is specified by I<spec>. The following types are
1122 available:
1123
1124 =over 4
1125
1126 =item C<PTH_EVENT_FD>
1127
1128 This is a file descriptor event. One or more of C<PTH_UNTIL_FD_READABLE>,
1129 C<PTH_UNTIL_FD_WRITEABLE> or C<PTH_UNTIL_FD_EXCEPTION> have to be OR-ed into
1130 I<spec> to specify on which state of the file descriptor you want to wait.  The
1131 file descriptor itself has to be given as an additional argument.  Example:
1132 `C<pth_event(PTH_EVENT_FD|PTH_UNTIL_FD_READABLE, fd)>'.
1133
1134 =item C<PTH_EVENT_SELECT>
1135
1136 This is a multiple file descriptor event modeled directly after the select(2)
1137 call (actually it is also used to implement pth_select(3) internally).  It's a
1138 convenient way to wait for a large set of file descriptors at once and at each
1139 file descriptor for a different type of state. Additionally as a nice
1140 side-effect one receives the number of file descriptors which causes the event
1141 to be occurred (using BSD semantics, i.e., when a file descriptor occurred in
1142 two sets it's counted twice). The arguments correspond directly to the
1143 select(2) function arguments except that there is no timeout argument (because
1144 timeouts already can be handled via C<PTH_EVENT_TIME> events).
1145
1146 Example: `C<pth_event(PTH_EVENT_SELECT, &rc, nfd, rfds, wfds, efds)>' where
1147 C<rc> has to be of type `C<int *>', C<nfd> has to be of type `C<int>' and
1148 C<rfds>, C<wfds> and C<efds> have to be of type `C<fd_set *>' (see
1149 select(2)). The number of occurred file descriptors are stored in C<rc>.
1150
1151 =item C<PTH_EVENT_SIGS>
1152
1153 This is a signal set event. The two additional arguments have to be a pointer
1154 to a signal set (type `C<sigset_t *>') and a pointer to a signal number
1155 variable (type `C<int *>').  This event waits until one of the signals in
1156 the signal set occurred.  As a result the occurred signal number is stored in
1157 the second additional argument. Keep in mind that the B<Pth> scheduler doesn't
1158 block signals automatically.  So when you want to wait for a signal with this
1159 event you've to block it via sigprocmask(2) or it will be delivered without
1160 your notice. Example: `C<sigemptyset(&set); sigaddset(&set, SIGINT);
1161 pth_event(PTH_EVENT_SIG, &set, &sig);>'.
1162
1163 =item C<PTH_EVENT_TIME>
1164
1165 This is a time point event. The additional argument has to be of type
1166 C<pth_time_t> (usually on-the-fly generated via pth_time(3)). This events
1167 waits until the specified time point has elapsed. Keep in mind that the value
1168 is an absolute time point and not an offset. When you want to wait for a
1169 specified amount of time, you've to add the current time to the offset
1170 (usually on-the-fly achieved via pth_timeout(3)).  Example:
1171 `C<pth_event(PTH_EVENT_TIME, pth_timeout(2,0))>'.
1172
1173 =item C<PTH_EVENT_MSG>
1174
1175 This is a message port event. The additional argument has to be of type
1176 C<pth_msgport_t>. This events waits until one or more messages were received
1177 on the specified message port.  Example: `C<pth_event(PTH_EVENT_MSG, mp)>'.
1178
1179 =item C<PTH_EVENT_TID>
1180
1181 This is a thread event. The additional argument has to be of type C<pth_t>.
1182 One of C<PTH_UNTIL_TID_NEW>, C<PTH_UNTIL_TID_READY>, C<PTH_UNTIL_TID_WAITING>
1183 or C<PTH_UNTIL_TID_DEAD> has to be OR-ed into I<spec> to specify on which
1184 state of the thread you want to wait.  Example:
1185 `C<pth_event(PTH_EVENT_TID|PTH_UNTIL_TID_DEAD, tid)>'.
1186
1187 =item C<PTH_EVENT_FUNC>
1188
1189 This is a custom callback function event. Three additional arguments
1190 have to be given with the following types: `C<int (*)(void *)>',
1191 `C<void *>' and `C<pth_time_t>'. The first is a function pointer to
1192 a check function and the second argument is a user-supplied context
1193 value which is passed to this function. The scheduler calls this
1194 function on a regular basis (on his own scheduler stack, so be very
1195 careful!) and the thread is kept sleeping while the function returns
1196 C<FALSE>. Once it returned C<TRUE> the thread will be awakened. The
1197 check interval is defined by the third argument, i.e., the check
1198 function is polled again not until this amount of time elapsed. Example:
1199 `C<pth_event(PTH_EVENT_FUNC, func, arg, pth_time(0,500000))>'.
1200
1201 =back
1202
1203 =item unsigned long B<pth_event_typeof>(pth_event_t I<ev>);
1204
1205 This returns the type of event I<ev>. It's a combination of the describing
1206 C<PTH_EVENT_XX> and C<PTH_UNTIL_XX> value. This is especially useful to know
1207 which arguments have to be supplied to the pth_event_extract(3) function.
1208
1209 =item int B<pth_event_extract>(pth_event_t I<ev>, ...);
1210
1211 When pth_event(3) is treated like sprintf(3), then this function is
1212 sscanf(3), i.e., it is the inverse operation of pth_event(3). This means that
1213 it can be used to extract the ingredients of an event.  The ingredients are
1214 stored into variables which are given as pointers on the variable argument
1215 list.  Which pointers have to be present depends on the event type and has to
1216 be determined by the caller before via pth_event_typeof(3).
1217
1218 To make it clear, when you constructed I<ev> via `C<ev =
1219 pth_event(PTH_EVENT_FD, fd);>' you have to extract it via
1220 `C<pth_event_extract(ev, &fd)>', etc. For multiple arguments of an event the
1221 order of the pointer arguments is the same as for pth_event(3). But always
1222 keep in mind that you have to always supply I<pointers> to I<variables> and
1223 these variables have to be of the same type as the argument of pth_event(3)
1224 required.
1225
1226 =item pth_event_t B<pth_event_concat>(pth_event_t I<ev>, ...);
1227
1228 This concatenates one or more additional event rings to the event ring I<ev>
1229 and returns I<ev>. The end of the argument list has to be marked with a
1230 C<NULL> argument. Use this function to create real events rings out of the
1231 single-event rings created by pth_event(3).
1232
1233 =item pth_event_t B<pth_event_isolate>(pth_event_t I<ev>);
1234
1235 This isolates the event I<ev> from possibly appended events in the event ring.
1236 When in I<ev> only one event exists, this returns C<NULL>. When remaining
1237 events exists, they form a new event ring which is returned.
1238
1239 =item pth_event_t B<pth_event_walk>(pth_event_t I<ev>, int I<direction>);
1240
1241 This walks to the next (when I<direction> is C<PTH_WALK_NEXT>) or previews
1242 (when I<direction> is C<PTH_WALK_PREV>) event in the event ring I<ev> and
1243 returns this new reached event. Additionally C<PTH_UNTIL_OCCURRED> can be
1244 OR-ed into I<direction> to walk to the next/previous occurred event in the
1245 ring I<ev>.
1246
1247 =item pth_status_t B<pth_event_status>(pth_event_t I<ev>);
1248
1249 This returns the status of event I<ev>. This is a fast operation
1250 because only a tag on I<ev> is checked which was either set or still
1251 not set by the scheduler. In other words: This doesn't check the
1252 event itself, it just checks the last knowledge of the scheduler. The
1253 possible returned status codes are: C<PTH_STATUS_PENDING> (event is
1254 still pending), C<PTH_STATUS_OCCURRED> (event successfully occurred),
1255 C<PTH_STATUS_FAILED> (event failed).
1256
1257 =item int B<pth_event_free>(pth_event_t I<ev>, int I<mode>);
1258
1259 This deallocates the event I<ev> (when I<mode> is C<PTH_FREE_THIS>) or all
1260 events appended to the event ring under I<ev> (when I<mode> is
1261 C<PTH_FREE_ALL>).
1262
1263 =back
1264
1265 =head2 Key-Based Storage
1266
1267 The following functions provide thread-local storage through unique keys
1268 similar to the POSIX B<Pthread> API. Use this for thread specific global data.
1269
1270 =over 4
1271
1272 =item int B<pth_key_create>(pth_key_t *I<key>, void (*I<func>)(void *));
1273
1274 This created a new unique key and stores it in I<key>.  Additionally I<func>
1275 can specify a destructor function which is called on the current threads
1276 termination with the I<key>.
1277
1278 =item int B<pth_key_delete>(pth_key_t I<key>);
1279
1280 This explicitly destroys a key I<key>.
1281
1282 =item int B<pth_key_setdata>(pth_key_t I<key>, const void *I<value>);
1283
1284 This stores I<value> under I<key>.
1285
1286 =item void *B<pth_key_getdata>(pth_key_t I<key>);
1287
1288 This retrieves the value under I<key>.
1289
1290 =back
1291
1292 =head2 Message Port Communication
1293
1294 The following functions provide message ports which can be used for efficient
1295 and flexible inter-thread communication.
1296
1297 =over 4
1298
1299 =item pth_msgport_t B<pth_msgport_create>(const char *I<name>);
1300
1301 This returns a pointer to a new message port. If name I<name>
1302 is not C<NULL>, the I<name> can be used by other threads via
1303 pth_msgport_find(3) to find the message port in case they do not know
1304 directly the pointer to the message port.
1305
1306 =item void B<pth_msgport_destroy>(pth_msgport_t I<mp>);
1307
1308 This destroys a message port I<mp>. Before all pending messages on it are
1309 replied to their origin message port.
1310
1311 =item pth_msgport_t B<pth_msgport_find>(const char *I<name>);
1312
1313 This finds a message port in the system by I<name> and returns the pointer to
1314 it.
1315
1316 =item int B<pth_msgport_pending>(pth_msgport_t I<mp>);
1317
1318 This returns the number of pending messages on message port I<mp>.
1319
1320 =item int B<pth_msgport_put>(pth_msgport_t I<mp>, pth_message_t *I<m>);
1321
1322 This puts (or sends) a message I<m> to message port I<mp>.
1323
1324 =item pth_message_t *B<pth_msgport_get>(pth_msgport_t I<mp>);
1325
1326 This gets (or receives) the top message from message port I<mp>.  Incoming
1327 messages are always kept in a queue, so there can be more pending messages, of
1328 course.
1329
1330 =item int B<pth_msgport_reply>(pth_message_t *I<m>);
1331
1332 This replies a message I<m> to the message port of the sender.
1333
1334 =back
1335
1336 =head2 Thread Cleanups
1337
1338 Per-thread cleanup functions.
1339
1340 =over 4
1341
1342 =item int B<pth_cleanup_push>(void (*I<handler>)(void *), void *I<arg>);
1343
1344 This pushes the routine I<handler> onto the stack of cleanup routines for the
1345 current thread.  These routines are called in LIFO order when the thread
1346 terminates.
1347
1348 =item int B<pth_cleanup_pop>(int I<execute>);
1349
1350 This pops the top-most routine from the stack of cleanup routines for the
1351 current thread. When I<execute> is C<TRUE> the routine is additionally called.
1352
1353 =back
1354
1355 =head2 Process Forking
1356
1357 The following functions provide some special support for process forking
1358 situations inside the threading environment.
1359
1360 =over 4
1361
1362 =item int B<pth_atfork_push>(void (*I<prepare>)(void *), void (*)(void *I<parent>), void (*)(void *I<child>), void *I<arg>);
1363
1364 This function declares forking handlers to be called before and after
1365 pth_fork(3), in the context of the thread that called pth_fork(3). The
1366 I<prepare> handler is called before fork(2) processing commences. The
1367 I<parent> handler is called   after fork(2) processing completes in the parent
1368 process.  The I<child> handler is called after fork(2) processing completed in
1369 the child process. If no handling is desired at one or more of these three
1370 points, the corresponding handler can be given as C<NULL>.  Each handler is
1371 called with I<arg> as the argument.
1372
1373 The order of calls to pth_atfork_push(3) is significant. The I<parent> and
1374 I<child> handlers are called in the order in which they were established by
1375 calls to pth_atfork_push(3), i.e., FIFO. The I<prepare> fork handlers are
1376 called in the opposite order, i.e., LIFO.
1377
1378 =item int B<pth_atfork_pop>(void);
1379
1380 This removes the top-most handlers on the forking handler stack which were
1381 established with the last pth_atfork_push(3) call. It returns C<FALSE> when no
1382 more handlers couldn't be removed from the stack.
1383
1384 =item pid_t B<pth_fork>(void);
1385
1386 This is a variant of fork(2) with the difference that the current thread only
1387 is forked into a separate process, i.e., in the parent process nothing changes
1388 while in the child process all threads are gone except for the scheduler and
1389 the calling thread. When you really want to duplicate all threads in the
1390 current process you should use fork(2) directly. But this is usually not
1391 reasonable. Additionally this function takes care of forking handlers as
1392 established by pth_fork_push(3).
1393
1394 =back
1395
1396 =head2 Synchronization
1397
1398 The following functions provide synchronization support via mutual exclusion
1399 locks (B<mutex>), read-write locks (B<rwlock>), condition variables (B<cond>)
1400 and barriers (B<barrier>). Keep in mind that in a non-preemptive threading
1401 system like B<Pth> this might sound unnecessary at the first look, because a
1402 thread isn't interrupted by the system. Actually when you have a critical code
1403 section which doesn't contain any pth_xxx() functions, you don't need any
1404 mutex to protect it, of course.
1405
1406 But when your critical code section contains any pth_xxx() function the chance
1407 is high that these temporarily switch to the scheduler. And this way other
1408 threads can make progress and enter your critical code section, too.  This is
1409 especially true for critical code sections which implicitly or explicitly use
1410 the event mechanism.
1411
1412 =over 4
1413
1414 =item int B<pth_mutex_init>(pth_mutex_t *I<mutex>);
1415
1416 This dynamically initializes a mutex variable of type `C<pth_mutex_t>'.
1417 Alternatively one can also use static initialization via `C<pth_mutex_t
1418 mutex = PTH_MUTEX_INIT>'.
1419
1420 =item int B<pth_mutex_acquire>(pth_mutex_t *I<mutex>, int I<try>, pth_event_t I<ev>);
1421
1422 This acquires a mutex I<mutex>.  If the mutex is already locked by another
1423 thread, the current threads execution is suspended until the mutex is unlocked
1424 again or additionally the extra events in I<ev> occurred (when I<ev> is not
1425 C<NULL>).  Recursive locking is explicitly supported, i.e., a thread is allowed
1426 to acquire a mutex more than once before its released. But it then also has be
1427 released the same number of times until the mutex is again lockable by others.
1428 When I<try> is C<TRUE> this function never suspends execution. Instead it
1429 returns C<FALSE> with C<errno> set to C<EBUSY>.
1430
1431 =item int B<pth_mutex_release>(pth_mutex_t *I<mutex>);
1432
1433 This decrements the recursion locking count on I<mutex> and when it is zero it
1434 releases the mutex I<mutex>.
1435
1436 =item int B<pth_rwlock_init>(pth_rwlock_t *I<rwlock>);
1437
1438 This dynamically initializes a read-write lock variable of type
1439 `C<pth_rwlock_t>'.  Alternatively one can also use static initialization
1440 via `C<pth_rwlock_t rwlock = PTH_RWLOCK_INIT>'.
1441
1442 =item int B<pth_rwlock_acquire>(pth_rwlock_t *I<rwlock>, int I<op>, int I<try>, pth_event_t I<ev>);
1443
1444 This acquires a read-only (when I<op> is C<PTH_RWLOCK_RD>) or a read-write
1445 (when I<op> is C<PTH_RWLOCK_RW>) lock I<rwlock>. When the lock is only locked
1446 by other threads in read-only mode, the lock succeeds.  But when one thread
1447 holds a read-write lock, all locking attempts suspend the current thread until
1448 this lock is released again. Additionally in I<ev> events can be given to let
1449 the locking timeout, etc. When I<try> is C<TRUE> this function never suspends
1450 execution. Instead it returns C<FALSE> with C<errno> set to C<EBUSY>.
1451
1452 =item int B<pth_rwlock_release>(pth_rwlock_t *I<rwlock>);
1453
1454 This releases a previously acquired (read-only or read-write) lock.
1455
1456 =item int B<pth_cond_init>(pth_cond_t *I<cond>);
1457
1458 This dynamically initializes a condition variable variable of type
1459 `C<pth_cond_t>'.  Alternatively one can also use static initialization via
1460 `C<pth_cond_t cond = PTH_COND_INIT>'.
1461
1462 =item int B<pth_cond_await>(pth_cond_t *I<cond>, pth_mutex_t *I<mutex>, pth_event_t I<ev>);
1463
1464 This awaits a condition situation. The caller has to follow the semantics of
1465 the POSIX condition variables: I<mutex> has to be acquired before this
1466 function is called. The execution of the current thread is then suspended
1467 either until the events in I<ev> occurred (when I<ev> is not C<NULL>) or
1468 I<cond> was notified by another thread via pth_cond_notify(3).  While the
1469 thread is waiting, I<mutex> is released. Before it returns I<mutex> is
1470 reacquired.
1471
1472 =item int B<pth_cond_notify>(pth_cond_t *I<cond>, int I<broadcast>);
1473
1474 This notified one or all threads which are waiting on I<cond>.  When
1475 I<broadcast> is C<TRUE> all thread are notified, else only a single
1476 (unspecified) one.
1477
1478 =item int B<pth_barrier_init>(pth_barrier_t *I<barrier>, int I<threshold>);
1479
1480 This dynamically initializes a barrier variable of type `C<pth_barrier_t>'.
1481 Alternatively one can also use static initialization via `C<pth_barrier_t
1482 barrier = PTH_BARRIER_INIT(>I<threadhold>C<)>'.
1483
1484 =item int B<pth_barrier_reach>(pth_barrier_t *I<barrier>);
1485
1486 This function reaches a barrier I<barrier>. If this is the last thread (as
1487 specified by I<threshold> on init of I<barrier>) all threads are awakened.
1488 Else the current thread is suspended until the last thread reached the barrier
1489 and this way awakes all threads. The function returns (beside C<FALSE> on
1490 error) the value C<TRUE> for any thread which neither reached the barrier as
1491 the first nor the last thread; C<PTH_BARRIER_HEADLIGHT> for the thread which
1492 reached the barrier as the first thread and C<PTH_BARRIER_TAILLIGHT> for the
1493 thread which reached the barrier as the last thread.
1494
1495 =back
1496
1497 =head2 User-Space Context
1498
1499 The following functions provide a stand-alone sub-API for user-space
1500 context switching. It internally is based on the same underlying machine
1501 context switching mechanism the threads in B<GNU Pth> are based on.
1502 Hence these functions you can use for implementing your own simple
1503 user-space threads. The C<pth_uctx_t> context is somewhat modeled after
1504 POSIX ucontext(3).
1505
1506 The time required to create (via pth_uctx_make(3)) a user-space context
1507 can range from just a few microseconds up to a more dramatical time
1508 (depending on the machine context switching method which is available on
1509 the platform). On the other hand, the raw performance in switching the
1510 user-space contexts is always very good (nearly independent of the used
1511 machine context switching method). For instance, on an Intel Pentium-III
1512 CPU with 800Mhz running under FreeBSD 4 one usually achieves about
1513 260,000 user-space context switches (via pth_uctx_switch(3)) per second.
1514
1515 =over 4
1516
1517 =item int B<pth_uctx_create>(pth_uctx_t *I<uctx>);
1518
1519 This function creates a user-space context and stores it into I<uctx>.
1520 There is still no underlying user-space context configured. You still
1521 have to do this with pth_uctx_make(3). On success, this function returns
1522 C<TRUE>, else C<FALSE>.
1523
1524 =item int B<pth_uctx_make>(pth_uctx_t I<uctx>, char *I<sk_addr>, size_t I<sk_size>, const sigset_t *I<sigmask>, void (*I<start_func>)(void *), void *I<start_arg>, pth_uctx_t I<uctx_after>);
1525
1526 This function makes a new user-space context in I<uctx> which will
1527 operate on the run-time stack I<sk_addr> (which is of maximum
1528 size I<sk_size>), with the signals in I<sigmask> blocked (if
1529 I<sigmask> is not C<NULL>) and starting to execute with the call
1530 I<start_func>(I<start_arg>). If I<sk_addr> is C<NULL>, a stack
1531 is dynamically allocated. The stack size I<sk_size> has to be at
1532 least 16384 (16KB). If the start function I<start_func> returns and
1533 I<uctx_after> is not C<NULL>, an implicit user-space context switch
1534 to this context is performed. Else (if I<uctx_after> is C<NULL>) the
1535 process is terminated with exit(3). This function is somewhat modeled
1536 after POSIX makecontext(3). On success, this function returns C<TRUE>,
1537 else C<FALSE>.
1538
1539 =item int B<pth_uctx_switch>(pth_uctx_t I<uctx_from>, pth_uctx_t I<uctx_to>);
1540
1541 This function saves the current user-space context in I<uctx_from> for
1542 later restoring by another call to pth_uctx_switch(3) and restores
1543 the new user-space context from I<uctx_to>, which previously had to
1544 be set with either a previous call to pth_uctx_switch(3) or initially
1545 by pth_uctx_make(3). This function is somewhat modeled after POSIX
1546 swapcontext(3). If I<uctx_from> or I<uctx_to> are C<NULL> or if
1547 I<uctx_to> contains no valid user-space context, C<FALSE> is returned
1548 instead of C<TRUE>. These are the only errors possible.
1549
1550 =item int B<pth_uctx_destroy>(pth_uctx_t I<uctx>);
1551
1552 This function destroys the user-space context in I<uctx>. The run-time
1553 stack associated with the user-space context is deallocated only if it
1554 was not given by the application (see I<sk_addr> of pth_uctx_create(3)).
1555 If I<uctx> is C<NULL>, C<FALSE> is returned instead of C<TRUE>. This is
1556 the only error possible.
1557
1558 =back
1559
1560 =head2 Generalized POSIX Replacement API
1561
1562 The following functions are generalized replacements functions for the POSIX
1563 API, i.e., they are similar to the functions under `B<Standard POSIX
1564 Replacement API>' but all have an additional event argument which can be used
1565 for timeouts, etc.
1566
1567 =over 4
1568
1569 =item int B<pth_sigwait_ev>(const sigset_t *I<set>, int *I<sig>, pth_event_t I<ev>);
1570
1571 This is equal to pth_sigwait(3) (see below), but has an additional event
1572 argument I<ev>. When pth_sigwait(3) suspends the current threads execution it
1573 usually only uses the signal event on I<set> to awake. With this function any
1574 number of extra events can be used to awake the current thread (remember that
1575 I<ev> actually is an event I<ring>).
1576
1577 =item int B<pth_connect_ev>(int I<s>, const struct sockaddr *I<addr>, socklen_t I<addrlen>, pth_event_t I<ev>);
1578
1579 This is equal to pth_connect(3) (see below), but has an additional event
1580 argument I<ev>. When pth_connect(3) suspends the current threads execution it
1581 usually only uses the I/O event on I<s> to awake. With this function any
1582 number of extra events can be used to awake the current thread (remember that
1583 I<ev> actually is an event I<ring>).
1584
1585 =item int B<pth_accept_ev>(int I<s>, struct sockaddr *I<addr>, socklen_t *I<addrlen>, pth_event_t I<ev>);
1586
1587 This is equal to pth_accept(3) (see below), but has an additional event
1588 argument I<ev>. When pth_accept(3) suspends the current threads execution it
1589 usually only uses the I/O event on I<s> to awake. With this function any
1590 number of extra events can be used to awake the current thread (remember that
1591 I<ev> actually is an event I<ring>).
1592
1593 =item int B<pth_select_ev>(int I<nfd>, fd_set *I<rfds>, fd_set *I<wfds>, fd_set *I<efds>, struct timeval *I<timeout>, pth_event_t I<ev>);
1594
1595 This is equal to pth_select(3) (see below), but has an additional event
1596 argument I<ev>. When pth_select(3) suspends the current threads execution it
1597 usually only uses the I/O event on I<rfds>, I<wfds> and I<efds> to awake. With
1598 this function any number of extra events can be used to awake the current
1599 thread (remember that I<ev> actually is an event I<ring>).
1600
1601 =item int B<pth_poll_ev>(struct pollfd *I<fds>, unsigned int I<nfd>, int I<timeout>, pth_event_t I<ev>);
1602
1603 This is equal to pth_poll(3) (see below), but has an additional event argument
1604 I<ev>. When pth_poll(3) suspends the current threads execution it usually only
1605 uses the I/O event on I<fds> to awake. With this function any number of extra
1606 events can be used to awake the current thread (remember that I<ev> actually
1607 is an event I<ring>).
1608
1609 =item ssize_t B<pth_read_ev>(int I<fd>, void *I<buf>, size_t I<nbytes>, pth_event_t I<ev>);
1610
1611 This is equal to pth_read(3) (see below), but has an additional event argument
1612 I<ev>. When pth_read(3) suspends the current threads execution it usually only
1613 uses the I/O event on I<fd> to awake. With this function any number of extra
1614 events can be used to awake the current thread (remember that I<ev> actually
1615 is an event I<ring>).
1616
1617 =item ssize_t B<pth_readv_ev>(int I<fd>, const struct iovec *I<iovec>, int I<iovcnt>, pth_event_t I<ev>);
1618
1619 This is equal to pth_readv(3) (see below), but has an additional event
1620 argument I<ev>. When pth_readv(3) suspends the current threads execution it
1621 usually only uses the I/O event on I<fd> to awake. With this function any
1622 number of extra events can be used to awake the current thread (remember that
1623 I<ev> actually is an event I<ring>).
1624
1625 =item ssize_t B<pth_write_ev>(int I<fd>, const void *I<buf>, size_t I<nbytes>, pth_event_t I<ev>);
1626
1627 This is equal to pth_write(3) (see below), but has an additional event argument
1628 I<ev>. When pth_write(3) suspends the current threads execution it usually
1629 only uses the I/O event on I<fd> to awake. With this function any number of
1630 extra events can be used to awake the current thread (remember that I<ev>
1631 actually is an event I<ring>).
1632
1633 =item ssize_t B<pth_writev_ev>(int I<fd>, const struct iovec *I<iovec>, int I<iovcnt>, pth_event_t I<ev>);
1634
1635 This is equal to pth_writev(3) (see below), but has an additional event
1636 argument I<ev>. When pth_writev(3) suspends the current threads execution it
1637 usually only uses the I/O event on I<fd> to awake. With this function any
1638 number of extra events can be used to awake the current thread (remember that
1639 I<ev> actually is an event I<ring>).
1640
1641 =item ssize_t B<pth_recv_ev>(int I<fd>, void *I<buf>, size_t I<nbytes>, int I<flags>, pth_event_t I<ev>);
1642
1643 This is equal to pth_recv(3) (see below), but has an additional event
1644 argument I<ev>. When pth_recv(3) suspends the current threads execution it
1645 usually only uses the I/O event on I<fd> to awake. With this function any
1646 number of extra events can be used to awake the current thread (remember that
1647 I<ev> actually is an event I<ring>).
1648
1649 =item ssize_t B<pth_recvfrom_ev>(int I<fd>, void *I<buf>, size_t I<nbytes>, int I<flags>, struct sockaddr *I<from>, socklen_t *I<fromlen>, pth_event_t I<ev>);
1650
1651 This is equal to pth_recvfrom(3) (see below), but has an additional event
1652 argument I<ev>. When pth_recvfrom(3) suspends the current threads execution it
1653 usually only uses the I/O event on I<fd> to awake. With this function any
1654 number of extra events can be used to awake the current thread (remember that
1655 I<ev> actually is an event I<ring>).
1656
1657 =item ssize_t B<pth_send_ev>(int I<fd>, const void *I<buf>, size_t I<nbytes>, int I<flags>, pth_event_t I<ev>);
1658
1659 This is equal to pth_send(3) (see below), but has an additional event
1660 argument I<ev>. When pth_send(3) suspends the current threads execution it
1661 usually only uses the I/O event on I<fd> to awake. With this function any
1662 number of extra events can be used to awake the current thread (remember that
1663 I<ev> actually is an event I<ring>).
1664
1665 =item ssize_t B<pth_sendto_ev>(int I<fd>, const void *I<buf>, size_t I<nbytes>, int I<flags>, const struct sockaddr *I<to>, socklen_t I<tolen>, pth_event_t I<ev>);
1666
1667 This is equal to pth_sendto(3) (see below), but has an additional event
1668 argument I<ev>. When pth_sendto(3) suspends the current threads execution it
1669 usually only uses the I/O event on I<fd> to awake. With this function any
1670 number of extra events can be used to awake the current thread (remember that
1671 I<ev> actually is an event I<ring>).
1672
1673 =back
1674
1675 =head2 Standard POSIX Replacement API
1676
1677 The following functions are standard replacements functions for the POSIX API.
1678 The difference is mainly that they suspend the current thread only instead of
1679 the whole process in case the file descriptors will block.
1680
1681 =over 4
1682
1683 =item int B<pth_nanosleep>(const struct timespec *I<rqtp>, struct timespec *I<rmtp>);
1684
1685 This is a variant of the POSIX nanosleep(3) function. It suspends the
1686 current threads execution until the amount of time in I<rqtp> elapsed.
1687 The thread is guaranteed to not wake up before this time, but because
1688 of the non-preemptive scheduling nature of B<Pth>, it can be awakened
1689 later, of course. If I<rmtp> is not C<NULL>, the C<timespec> structure
1690 it references is updated to contain the unslept amount (the request time
1691 minus the time actually slept time). The difference between nanosleep(3)
1692 and pth_nanosleep(3) is that that pth_nanosleep(3) suspends only the
1693 execution of the current thread and not the whole process.
1694
1695 =item int B<pth_usleep>(unsigned int I<usec>);
1696
1697 This is a variant of the 4.3BSD usleep(3) function. It suspends the current
1698 threads execution until I<usec> microseconds (= I<usec>*1/1000000 sec)
1699 elapsed.  The thread is guaranteed to not wake up before this time, but
1700 because of the non-preemptive scheduling nature of B<Pth>, it can be awakened
1701 later, of course.  The difference between usleep(3) and pth_usleep(3) is that
1702 that pth_usleep(3) suspends only the execution of the current thread and not
1703 the whole process.
1704
1705 =item unsigned int B<pth_sleep>(unsigned int I<sec>);
1706
1707 This is a variant of the POSIX sleep(3) function. It suspends the current
1708 threads execution until I<sec> seconds elapsed.  The thread is guaranteed to
1709 not wake up before this time, but because of the non-preemptive scheduling
1710 nature of B<Pth>, it can be awakened later, of course.  The difference between
1711 sleep(3) and pth_sleep(3) is that pth_sleep(3) suspends only the
1712 execution of the current thread and not the whole process.
1713
1714 =item pid_t B<pth_waitpid>(pid_t I<pid>, int *I<status>, int I<options>);
1715
1716 This is a variant of the POSIX waitpid(2) function. It suspends the
1717 current threads execution until I<status> information is available for a
1718 terminated child process I<pid>.  The difference between waitpid(2) and
1719 pth_waitpid(3) is that pth_waitpid(3) suspends only the execution of the
1720 current thread and not the whole process.  For more details about the
1721 arguments and return code semantics see waitpid(2).
1722
1723 =item int B<pth_system>(const char *I<cmd>);
1724
1725 This is a variant of the POSIX system(3) function. It executes the
1726 shell command I<cmd> with Bourne Shell (C<sh>) and suspends the current
1727 threads execution until this command terminates. The difference between
1728 system(3) and pth_system(3) is that pth_system(3) suspends only
1729 the execution of the current thread and not the whole process. For more
1730 details about the arguments and return code semantics see system(3).
1731
1732 =item int B<pth_sigmask>(int I<how>, const sigset_t *I<set>, sigset_t *I<oset>)
1733
1734 This is the B<Pth> thread-related equivalent of POSIX sigprocmask(2) respectively
1735 pthread_sigmask(3). The arguments I<how>, I<set> and I<oset> directly relate
1736 to sigprocmask(2), because B<Pth> internally just uses sigprocmask(2) here. So
1737 alternatively you can also directly call sigprocmask(2), but for consistency
1738 reasons you should use this function pth_sigmask(3).
1739
1740 =item int B<pth_sigwait>(const sigset_t *I<set>, int *I<sig>);
1741
1742 This is a variant of the POSIX.1c sigwait(3) function. It suspends the current
1743 threads execution until a signal in I<set> occurred and stores the signal
1744 number in I<sig>. The important point is that the signal is not delivered to a
1745 signal handler. Instead it's caught by the scheduler only in order to awake
1746 the pth_sigwait() call. The trick and noticeable point here is that this way
1747 you get an asynchronous aware application that is written completely
1748 synchronously. When you think about the problem of I<asynchronous safe>
1749 functions you should recognize that this is a great benefit.
1750
1751 =item int B<pth_connect>(int I<s>, const struct sockaddr *I<addr>, socklen_t I<addrlen>);
1752
1753 This is a variant of the 4.2BSD connect(2) function. It establishes a
1754 connection on a socket I<s> to target specified in I<addr> and I<addrlen>.
1755 The difference between connect(2) and pth_connect(3) is that
1756 pth_connect(3) suspends only the execution of the current thread and not the
1757 whole process.  For more details about the arguments and return code semantics
1758 see connect(2).
1759
1760 =item int B<pth_accept>(int I<s>, struct sockaddr *I<addr>, socklen_t *I<addrlen>);
1761
1762 This is a variant of the 4.2BSD accept(2) function. It accepts a connection on
1763 a socket by extracting the first connection request on the queue of pending
1764 connections, creating a new socket with the same properties of I<s> and
1765 allocates a new file descriptor for the socket (which is returned).  The
1766 difference between accept(2) and pth_accept(3) is that pth_accept(3)
1767 suspends only the execution of the current thread and not the whole process.
1768 For more details about the arguments and return code semantics see accept(2).
1769
1770 =item int B<pth_select>(int I<nfd>, fd_set *I<rfds>, fd_set *I<wfds>, fd_set *I<efds>, struct timeval *I<timeout>);
1771
1772 This is a variant of the 4.2BSD select(2) function.  It examines the I/O
1773 descriptor sets whose addresses are passed in I<rfds>, I<wfds>, and I<efds> to
1774 see if some of their descriptors are ready for reading, are ready for writing,
1775 or have an exceptional condition pending, respectively.  For more details
1776 about the arguments and return code semantics see select(2).
1777
1778 =item int B<pth_pselect>(int I<nfd>, fd_set *I<rfds>, fd_set *I<wfds>, fd_set *I<efds>, const struct timespec *I<timeout>, const sigset_t *I<sigmask>);
1779
1780 This is a variant of the POSIX pselect(2) function, which in turn
1781 is a stronger variant of 4.2BSD select(2). The difference is that
1782 the higher-resolution C<struct timespec> is passed instead of the
1783 lower-resolution C<struct timeval> and that a signal mask is specified
1784 which is temporarily set while waiting for input. For more details about
1785 the arguments and return code semantics see pselect(2) and select(2).
1786
1787 =item int B<pth_poll>(struct pollfd *I<fds>, unsigned int I<nfd>, int I<timeout>);
1788
1789 This is a variant of the SysV poll(2) function. It examines the I/O
1790 descriptors which are passed in the array I<fds> to see if some of them are
1791 ready for reading, are ready for writing, or have an exceptional condition
1792 pending, respectively. For more details about the arguments and return code
1793 semantics see poll(2).
1794
1795 =item ssize_t B<pth_read>(int I<fd>, void *I<buf>, size_t I<nbytes>);
1796
1797 This is a variant of the POSIX read(2) function. It reads up to I<nbytes>
1798 bytes into I<buf> from file descriptor I<fd>.  The difference between read(2)
1799 and pth_read(2) is that pth_read(2) suspends execution of the current
1800 thread until the file descriptor is ready for reading. For more details about
1801 the arguments and return code semantics see read(2).
1802
1803 =item ssize_t B<pth_readv>(int I<fd>, const struct iovec *I<iovec>, int I<iovcnt>);
1804
1805 This is a variant of the POSIX readv(2) function. It reads data from
1806 file descriptor I<fd> into the first I<iovcnt> rows of the I<iov> vector.  The
1807 difference between readv(2) and pth_readv(2) is that pth_readv(2)
1808 suspends execution of the current thread until the file descriptor is ready for
1809 reading. For more details about the arguments and return code semantics see
1810 readv(2).
1811
1812 =item ssize_t B<pth_write>(int I<fd>, const void *I<buf>, size_t I<nbytes>);
1813
1814 This is a variant of the POSIX write(2) function. It writes I<nbytes> bytes
1815 from I<buf> to file descriptor I<fd>.  The difference between write(2) and
1816 pth_write(2) is that pth_write(2) suspends execution of the current
1817 thread until the file descriptor is ready for writing.  For more details about
1818 the arguments and return code semantics see write(2).
1819
1820 =item ssize_t B<pth_writev>(int I<fd>, const struct iovec *I<iovec>, int I<iovcnt>);
1821
1822 This is a variant of the POSIX writev(2) function. It writes data to
1823 file descriptor I<fd> from the first I<iovcnt> rows of the I<iov> vector.  The
1824 difference between writev(2) and pth_writev(2) is that pth_writev(2)
1825 suspends execution of the current thread until the file descriptor is ready for
1826 reading. For more details about the arguments and return code semantics see
1827 writev(2).
1828
1829 =item ssize_t B<pth_pread>(int I<fd>, void *I<buf>, size_t I<nbytes>, off_t I<offset>);
1830
1831 This is a variant of the POSIX pread(3) function.  It performs the same action
1832 as a regular read(2), except that it reads from a given position in the file
1833 without changing the file pointer.  The first three arguments are the same as
1834 for pth_read(3) with the addition of a fourth argument I<offset> for the
1835 desired position inside the file.
1836
1837 =item ssize_t B<pth_pwrite>(int I<fd>, const void *I<buf>, size_t I<nbytes>, off_t I<offset>);
1838
1839 This is a variant of the POSIX pwrite(3) function.  It performs the same
1840 action as a regular write(2), except that it writes to a given position in the
1841 file without changing the file pointer. The first three arguments are the same
1842 as for pth_write(3) with the addition of a fourth argument I<offset> for the
1843 desired position inside the file.
1844
1845 =item ssize_t B<pth_recv>(int I<fd>, void *I<buf>, size_t I<nbytes>, int I<flags>);
1846
1847 This is a variant of the SUSv2 recv(2) function and equal to
1848 ``pth_recvfrom(fd, buf, nbytes, flags, NULL, 0)''.
1849
1850 =item ssize_t B<pth_recvfrom>(int I<fd>, void *I<buf>, size_t I<nbytes>, int I<flags>, struct sockaddr *I<from>, socklen_t *I<fromlen>);
1851
1852 This is a variant of the SUSv2 recvfrom(2) function. It reads up to
1853 I<nbytes> bytes into I<buf> from file descriptor I<fd> while using
1854 I<flags> and I<from>/I<fromlen>. The difference between recvfrom(2) and
1855 pth_recvfrom(2) is that pth_recvfrom(2) suspends execution of the
1856 current thread until the file descriptor is ready for reading. For more
1857 details about the arguments and return code semantics see recvfrom(2).
1858
1859 =item ssize_t B<pth_send>(int I<fd>, const void *I<buf>, size_t I<nbytes>, int I<flags>);
1860
1861 This is a variant of the SUSv2 send(2) function and equal to
1862 ``pth_sendto(fd, buf, nbytes, flags, NULL, 0)''.
1863
1864 =item ssize_t B<pth_sendto>(int I<fd>, const void *I<buf>, size_t I<nbytes>, int I<flags>, const struct sockaddr *I<to>, socklen_t I<tolen>);
1865
1866 This is a variant of the SUSv2 sendto(2) function. It writes I<nbytes>
1867 bytes from I<buf> to file descriptor I<fd> while using I<flags> and
1868 I<to>/I<tolen>. The difference between sendto(2) and pth_sendto(2) is
1869 that pth_sendto(2) suspends execution of the current thread until
1870 the file descriptor is ready for writing. For more details about the
1871 arguments and return code semantics see sendto(2).
1872
1873 =back
1874
1875 =head1 EXAMPLE
1876
1877 The following example is a useless server which does nothing more than
1878 listening on TCP port 12345 and displaying the current time to the
1879 socket when a connection was established. For each incoming connection a
1880 thread is spawned. Additionally, to see more multithreading, a useless
1881 ticker thread runs simultaneously which outputs the current time to
1882 C<stderr> every 5 seconds. The example contains I<no> error checking and
1883 is I<only> intended to show you the look and feel of B<Pth>.
1884
1885  #include <stdio.h>
1886  #include <stdlib.h>
1887  #include <errno.h>
1888  #include <sys/types.h>
1889  #include <sys/socket.h>
1890  #include <netinet/in.h>
1891  #include <arpa/inet.h>
1892  #include <signal.h>
1893  #include <netdb.h>
1894  #include <unistd.h>
1895  #include "pth.h"
1896
1897  #define PORT 12345
1898
1899  /* the socket connection handler thread */
1900  static void *handler(void *_arg)
1901  {
1902      int fd = (int)_arg;
1903      time_t now;
1904      char *ct;
1905
1906      now = time(NULL);
1907      ct = ctime(&now);
1908      pth_write(fd, ct, strlen(ct));
1909      close(fd);
1910      return NULL;
1911  }
1912
1913  /* the stderr time ticker thread */
1914  static void *ticker(void *_arg)
1915  {
1916      time_t now;
1917      char *ct;
1918      float load;
1919
1920      for (;;) {
1921          pth_sleep(5);
1922          now = time(NULL);
1923          ct = ctime(&now);
1924          ct[strlen(ct)-1] = '\0';
1925          pth_ctrl(PTH_CTRL_GETAVLOAD, &load);
1926          printf("ticker: time: %s, average load: %.2f\n", ct, load);
1927      }
1928  }
1929
1930  /* the main thread/procedure */
1931  int main(int argc, char *argv[])
1932  {
1933      pth_attr_t attr;
1934      struct sockaddr_in sar;
1935      struct protoent *pe;
1936      struct sockaddr_in peer_addr;
1937      int peer_len;
1938      int sa, sw;
1939      int port;
1940
1941      pth_init();
1942      signal(SIGPIPE, SIG_IGN);
1943
1944      attr = pth_attr_new();
1945      pth_attr_set(attr, PTH_ATTR_NAME, "ticker");
1946      pth_attr_set(attr, PTH_ATTR_STACK_SIZE, 64*1024);
1947      pth_attr_set(attr, PTH_ATTR_JOINABLE, FALSE);
1948      pth_spawn(attr, ticker, NULL);
1949
1950      pe = getprotobyname("tcp");
1951      sa = socket(AF_INET, SOCK_STREAM, pe->p_proto);
1952      sar.sin_family = AF_INET;
1953      sar.sin_addr.s_addr = INADDR_ANY;
1954      sar.sin_port = htons(PORT);
1955      bind(sa, (struct sockaddr *)&sar, sizeof(struct sockaddr_in));
1956      listen(sa, 10);
1957
1958      pth_attr_set(attr, PTH_ATTR_NAME, "handler");
1959      for (;;) {
1960          peer_len = sizeof(peer_addr);
1961          sw = pth_accept(sa, (struct sockaddr *)&peer_addr, &peer_len);
1962          pth_spawn(attr, handler, (void *)sw);
1963      }
1964  }
1965
1966 =head1 BUILD ENVIRONMENTS
1967
1968 In this section we will discuss the canonical ways to establish the build
1969 environment for a B<Pth> based program. The possibilities supported by B<Pth>
1970 range from very simple environments to rather complex ones.
1971
1972 =head2 Manual Build Environment (Novice)
1973
1974 As a first example, assume we have the above test program staying in the
1975 source file C<foo.c>. Then we can create a very simple build environment by
1976 just adding the following C<Makefile>:
1977
1978  $ vi Makefile
1979  | CC      = cc
1980  | CFLAGS  = `pth-config --cflags`
1981  | LDFLAGS = `pth-config --ldflags`
1982  | LIBS    = `pth-config --libs`
1983  |
1984  | all: foo
1985  | foo: foo.o
1986  |     $(CC) $(LDFLAGS) -o foo foo.o $(LIBS)
1987  | foo.o: foo.c
1988  |     $(CC) $(CFLAGS) -c foo.c
1989  | clean:
1990  |     rm -f foo foo.o
1991
1992 This imports the necessary compiler and linker flags on-the-fly from the
1993 B<Pth> installation via its C<pth-config> program. This approach is
1994 straight-forward and works fine for small projects.
1995
1996 =head2 Autoconf Build Environment (Advanced)
1997
1998 The previous approach is simple but inflexible. First, to speed up
1999 building, it would be nice to not expand the compiler and linker flags
2000 every time the compiler is started. Second, it would be useful to
2001 also be able to build against uninstalled B<Pth>, that is, against
2002 a B<Pth> source tree which was just configured and built, but not
2003 installed. Third, it would be also useful to allow checking of the
2004 B<Pth> version to make sure it is at least a minimum required version.
2005 And finally, it would be also great to make sure B<Pth> works correctly
2006 by first performing some sanity compile and run-time checks. All this
2007 can be done if we use GNU B<autoconf> and the C<AC_CHECK_PTH> macro
2008 provided by B<Pth>. For this, we establish the following three files:
2009
2010 First we again need the C<Makefile>, but this time it contains B<autoconf>
2011 placeholders and additional cleanup targets. And we create it under the name
2012 C<Makefile.in>, because it is now an input file for B<autoconf>:
2013
2014  $ vi Makefile.in
2015  | CC      = @CC@
2016  | CFLAGS  = @CFLAGS@
2017  | LDFLAGS = @LDFLAGS@
2018  | LIBS    = @LIBS@
2019  |
2020  | all: foo
2021  | foo: foo.o
2022  |     $(CC) $(LDFLAGS) -o foo foo.o $(LIBS)
2023  | foo.o: foo.c
2024  |     $(CC) $(CFLAGS) -c foo.c
2025  | clean:
2026  |     rm -f foo foo.o
2027  | distclean:
2028  |     rm -f foo foo.o
2029  |     rm -f config.log config.status config.cache
2030  |     rm -f Makefile
2031
2032 Because B<autoconf> generates additional files, we added a canonical
2033 C<distclean> target which cleans this up. Secondly, we wrote
2034 C<configure.ac>, a (minimal) B<autoconf> script specification:
2035
2036  $ vi configure.ac
2037  | AC_INIT(Makefile.in)
2038  | AC_CHECK_PTH(1.3.0)
2039  | AC_OUTPUT(Makefile)
2040
2041 Then we let B<autoconf>'s C<aclocal> program generate for us an C<aclocal.m4>
2042 file containing B<Pth>'s C<AC_CHECK_PTH> macro. Then we generate the final
2043 C<configure> script out of this C<aclocal.m4> file and the C<configure.ac>
2044 file:
2045
2046  $ aclocal --acdir=`pth-config --acdir`
2047  $ autoconf
2048
2049 After these steps, the working directory should look similar to this:
2050
2051  $ ls -l
2052  -rw-r--r--  1 rse  users    176 Nov  3 11:11 Makefile.in
2053  -rw-r--r--  1 rse  users  15314 Nov  3 11:16 aclocal.m4
2054  -rwxr-xr-x  1 rse  users  52045 Nov  3 11:16 configure
2055  -rw-r--r--  1 rse  users     63 Nov  3 11:11 configure.ac
2056  -rw-r--r--  1 rse  users   4227 Nov  3 11:11 foo.c
2057
2058 If we now run C<configure> we get a correct C<Makefile> which
2059 immediately can be used to build C<foo> (assuming that B<Pth> is already
2060 installed somewhere, so that C<pth-config> is in C<$PATH>):
2061
2062  $ ./configure
2063  creating cache ./config.cache
2064  checking for gcc... gcc
2065  checking whether the C compiler (gcc   ) works... yes
2066  checking whether the C compiler (gcc   ) is a cross-compiler... no
2067  checking whether we are using GNU C... yes
2068  checking whether gcc accepts -g... yes
2069  checking how to run the C preprocessor... gcc -E
2070  checking for GNU Pth... version 1.3.0, installed under /usr/local
2071  updating cache ./config.cache
2072  creating ./config.status
2073  creating Makefile
2074  rse@en1:/e/gnu/pth/ac
2075  $ make
2076  gcc -g -O2 -I/usr/local/include -c foo.c
2077  gcc -L/usr/local/lib -o foo foo.o -lpth
2078
2079 If B<Pth> is installed in non-standard locations or C<pth-config>
2080 is not in C<$PATH>, one just has to drop the C<configure> script
2081 a note about the location by running C<configure> with the option
2082 C<--with-pth=>I<dir> (where I<dir> is the argument which was used with
2083 the C<--prefix> option when B<Pth> was installed).
2084
2085 =head2 Autoconf Build Environment with Local Copy of Pth (Expert)
2086
2087 Finally let us assume the C<foo> program stays under either a I<GPL> or
2088 I<LGPL> distribution license and we want to make it a stand-alone package for
2089 easier distribution and installation.  That is, we don't want to oblige the
2090 end-user to install B<Pth> just to allow our C<foo> package to
2091 compile. For this, it is a convenient practice to include the required
2092 libraries (here B<Pth>) into the source tree of the package (here C<foo>).
2093 B<Pth> ships with all necessary support to allow us to easily achieve this
2094 approach. Say, we want B<Pth> in a subdirectory named C<pth/> and this
2095 directory should be seamlessly integrated into the configuration and build
2096 process of C<foo>.
2097
2098 First we again start with the C<Makefile.in>, but this time it is a more
2099 advanced version which supports subdirectory movement:
2100
2101  $ vi Makefile.in
2102  | CC      = @CC@
2103  | CFLAGS  = @CFLAGS@
2104  | LDFLAGS = @LDFLAGS@
2105  | LIBS    = @LIBS@
2106  |
2107  | SUBDIRS = pth
2108  |
2109  | all: subdirs_all foo
2110  |
2111  | subdirs_all:
2112  |     @$(MAKE) $(MFLAGS) subdirs TARGET=all
2113  | subdirs_clean:
2114  |     @$(MAKE) $(MFLAGS) subdirs TARGET=clean
2115  | subdirs_distclean:
2116  |     @$(MAKE) $(MFLAGS) subdirs TARGET=distclean
2117  | subdirs:
2118  |     @for subdir in $(SUBDIRS); do \
2119  |         echo "===> $$subdir ($(TARGET))"; \
2120  |         (cd $$subdir; $(MAKE) $(MFLAGS) $(TARGET) || exit 1) || exit 1; \
2121  |         echo "<=== $$subdir"; \
2122  |     done
2123  |
2124  | foo: foo.o
2125  |     $(CC) $(LDFLAGS) -o foo foo.o $(LIBS)
2126  | foo.o: foo.c
2127  |     $(CC) $(CFLAGS) -c foo.c
2128  |
2129  | clean: subdirs_clean
2130  |     rm -f foo foo.o
2131  | distclean: subdirs_distclean
2132  |     rm -f foo foo.o
2133  |     rm -f config.log config.status config.cache
2134  |     rm -f Makefile
2135
2136 Then we create a slightly different B<autoconf> script C<configure.ac>:
2137
2138  $ vi configure.ac
2139  | AC_INIT(Makefile.in)
2140  | AC_CONFIG_AUX_DIR(pth)
2141  | AC_CHECK_PTH(1.3.0, subdir:pth --disable-tests)
2142  | AC_CONFIG_SUBDIRS(pth)
2143  | AC_OUTPUT(Makefile)
2144
2145 Here we provided a default value for C<foo>'s C<--with-pth> option as the
2146 second argument to C<AC_CHECK_PTH> which indicates that B<Pth> can be found in
2147 the subdirectory named C<pth/>. Additionally we specified that the
2148 C<--disable-tests> option of B<Pth> should be passed to the C<pth/>
2149 subdirectory, because we need only to build the B<Pth> library itself. And we
2150 added a C<AC_CONFIG_SUBDIR> call which indicates to B<autoconf> that it should
2151 configure the C<pth/> subdirectory, too. The C<AC_CONFIG_AUX_DIR> directive
2152 was added just to make B<autoconf> happy, because it wants to find a
2153 C<install.sh> or C<shtool> script if C<AC_CONFIG_SUBDIRS> is used.
2154
2155 Now we let B<autoconf>'s C<aclocal> program again generate for us an
2156 C<aclocal.m4> file with the contents of B<Pth>'s C<AC_CHECK_PTH> macro.
2157 Finally we generate the C<configure> script out of this C<aclocal.m4>
2158 file and the C<configure.ac> file.
2159
2160  $ aclocal --acdir=`pth-config --acdir`
2161  $ autoconf
2162
2163 Now we have to create the C<pth/> subdirectory itself. For this, we extract the
2164 B<Pth> distribution to the C<foo> source tree and just rename it to C<pth/>:
2165
2166  $ gunzip <pth-X.Y.Z.tar.gz | tar xvf -
2167  $ mv pth-X.Y.Z pth
2168
2169 Optionally to reduce the size of the C<pth/> subdirectory, we can strip down
2170 the B<Pth> sources to a minimum with the I<striptease> feature:
2171
2172  $ cd pth
2173  $ ./configure
2174  $ make striptease
2175  $ cd ..
2176
2177 After this the source tree of C<foo> should look similar to this:
2178
2179  $ ls -l
2180  -rw-r--r--  1 rse  users    709 Nov  3 11:51 Makefile.in
2181  -rw-r--r--  1 rse  users  16431 Nov  3 12:20 aclocal.m4
2182  -rwxr-xr-x  1 rse  users  57403 Nov  3 12:21 configure
2183  -rw-r--r--  1 rse  users    129 Nov  3 12:21 configure.ac
2184  -rw-r--r--  1 rse  users   4227 Nov  3 11:11 foo.c
2185  drwxr-xr-x  2 rse  users   3584 Nov  3 12:36 pth
2186  $ ls -l pth/
2187  -rw-rw-r--  1 rse  users   26344 Nov  1 20:12 COPYING
2188  -rw-rw-r--  1 rse  users    2042 Nov  3 12:36 Makefile.in
2189  -rw-rw-r--  1 rse  users    3967 Nov  1 19:48 README
2190  -rw-rw-r--  1 rse  users     340 Nov  3 12:36 README.1st
2191  -rw-rw-r--  1 rse  users   28719 Oct 31 17:06 config.guess
2192  -rw-rw-r--  1 rse  users   24274 Aug 18 13:31 config.sub
2193  -rwxrwxr-x  1 rse  users  155141 Nov  3 12:36 configure
2194  -rw-rw-r--  1 rse  users  162021 Nov  3 12:36 pth.c
2195  -rw-rw-r--  1 rse  users   18687 Nov  2 15:19 pth.h.in
2196  -rw-rw-r--  1 rse  users    5251 Oct 31 12:46 pth_acdef.h.in
2197  -rw-rw-r--  1 rse  users    2120 Nov  1 11:27 pth_acmac.h.in
2198  -rw-rw-r--  1 rse  users    2323 Nov  1 11:27 pth_p.h.in
2199  -rw-rw-r--  1 rse  users     946 Nov  1 11:27 pth_vers.c
2200  -rw-rw-r--  1 rse  users   26848 Nov  1 11:27 pthread.c
2201  -rw-rw-r--  1 rse  users   18772 Nov  1 11:27 pthread.h.in
2202  -rwxrwxr-x  1 rse  users   26188 Nov  3 12:36 shtool
2203
2204 Now when we configure and build the C<foo> package it looks similar to this:
2205
2206  $ ./configure
2207  creating cache ./config.cache
2208  checking for gcc... gcc
2209  checking whether the C compiler (gcc   ) works... yes
2210  checking whether the C compiler (gcc   ) is a cross-compiler... no
2211  checking whether we are using GNU C... yes
2212  checking whether gcc accepts -g... yes
2213  checking how to run the C preprocessor... gcc -E
2214  checking for GNU Pth... version 1.3.0, local under pth
2215  updating cache ./config.cache
2216  creating ./config.status
2217  creating Makefile
2218  configuring in pth
2219  running /bin/sh ./configure  --enable-subdir --enable-batch
2220  --disable-tests --cache-file=.././config.cache --srcdir=.
2221  loading cache .././config.cache
2222  checking for gcc... (cached) gcc
2223  checking whether the C compiler (gcc   ) works... yes
2224  checking whether the C compiler (gcc   ) is a cross-compiler... no
2225  [...]
2226  $ make
2227  ===> pth (all)
2228  ./shtool scpp -o pth_p.h -t pth_p.h.in -Dcpp -Cintern -M '==#==' pth.c
2229  pth_vers.c
2230  gcc -c -I. -O2 -pipe pth.c
2231  gcc -c -I. -O2 -pipe pth_vers.c
2232  ar rc libpth.a pth.o pth_vers.o
2233  ranlib libpth.a
2234  <=== pth
2235  gcc -g -O2 -Ipth -c foo.c
2236  gcc -Lpth -o foo foo.o -lpth
2237
2238 As you can see, B<autoconf> now automatically configures the local
2239 (stripped down) copy of B<Pth> in the subdirectory C<pth/> and the
2240 C<Makefile> automatically builds the subdirectory, too.
2241
2242 =head1 SYSTEM CALL WRAPPER FACILITY
2243
2244 B<Pth> per default uses an explicit API, including the system calls. For
2245 instance you've to explicitly use pth_read(3) when you need a thread-aware
2246 read(3) and cannot expect that by just calling read(3) only the current thread
2247 is blocked. Instead with the standard read(3) call the whole process will be
2248 blocked. But because for some applications (mainly those consisting of lots of
2249 third-party stuff) this can be inconvenient.  Here it's required that a call
2250 to read(3) `magically' means pth_read(3). The problem here is that such
2251 magic B<Pth> cannot provide per default because it's not really portable.
2252 Nevertheless B<Pth> provides a two step approach to solve this problem:
2253
2254 =head2 Soft System Call Mapping
2255
2256 This variant is available on all platforms and can I<always> be enabled by
2257 building B<Pth> with C<--enable-syscall-soft>. This then triggers some
2258 C<#define>'s in the C<pth.h> header which map for instance read(3) to
2259 pth_read(3), etc. Currently the following functions are mapped: fork(2),
2260 nanosleep(3), usleep(3), sleep(3), sigwait(3), waitpid(2), system(3),
2261 select(2), poll(2), connect(2), accept(2), read(2), write(2), recv(2),
2262 send(2), recvfrom(2), sendto(2).
2263
2264 The drawback of this approach is just that really all source files
2265 of the application where these function calls occur have to include
2266 C<pth.h>, of course. And this also means that existing libraries,
2267 including the vendor's B<stdio>, usually will still block the whole
2268 process if one of its I/O functions block.
2269
2270 =head2 Hard System Call Mapping
2271
2272 This variant is available only on those platforms where the syscall(2)
2273 function exists and there it can be enabled by building B<Pth> with
2274 C<--enable-syscall-hard>. This then builds wrapper functions (for instances
2275 read(3)) into the B<Pth> library which internally call the real B<Pth>
2276 replacement functions (pth_read(3)). Currently the following functions
2277 are mapped: fork(2), nanosleep(3), usleep(3), sleep(3), waitpid(2),
2278 system(3), select(2), poll(2), connect(2), accept(2), read(2), write(2).
2279
2280 The drawback of this approach is that it depends on syscall(2) interface
2281 and prototype conflicts can occur while building the wrapper functions
2282 due to different function signatures in the vendor C header files.
2283 But the advantage of this mapping variant is that the source files of
2284 the application where these function calls occur have not to include
2285 C<pth.h> and that existing libraries, including the vendor's B<stdio>,
2286 magically become thread-aware (and then block only the current thread).
2287
2288 =head1 IMPLEMENTATION NOTES
2289
2290 B<Pth> is very portable because it has only one part which perhaps has
2291 to be ported to new platforms (the machine context initialization). But
2292 it is written in a way which works on mostly all Unix platforms which
2293 support makecontext(2) or at least sigstack(2) or sigaltstack(2) [see
2294 C<pth_mctx.c> for details]. Any other B<Pth> code is POSIX and ANSI C
2295 based only.
2296
2297 The context switching is done via either SUSv2 makecontext(2) or POSIX
2298 make[sig]setjmp(3) and [sig]longjmp(3). Here all CPU registers, the
2299 program counter and the stack pointer are switched. Additionally the
2300 B<Pth> dispatcher switches also the global Unix C<errno> variable [see
2301 C<pth_mctx.c> for details] and the signal mask (either implicitly via
2302 sigsetjmp(3) or in an emulated way via explicit setprocmask(2) calls).
2303
2304 The B<Pth> event manager is mainly select(2) and gettimeofday(2) based,
2305 i.e., the current time is fetched via gettimeofday(2) once per context
2306 switch for time calculations and all I/O events are implemented via a
2307 single central select(2) call [see C<pth_sched.c> for details].
2308
2309 The thread control block management is done via virtual priority
2310 queues without any additional data structure overhead. For this, the
2311 queue linkage attributes are part of the thread control blocks and the
2312 queues are actually implemented as rings with a selected element as the
2313 entry point [see C<pth_tcb.h> and C<pth_pqueue.c> for details].
2314
2315 Most time critical code sections (especially the dispatcher and event
2316 manager) are speeded up by inline functions (implemented as ANSI C
2317 pre-processor macros). Additionally any debugging code is I<completely>
2318 removed from the source when not built with C<-DPTH_DEBUG> (see Autoconf
2319 C<--enable-debug> option), i.e., not only stub functions remain [see
2320 C<pth_debug.c> for details].
2321
2322 =head1 RESTRICTIONS
2323
2324 B<Pth> (intentionally) provides no replacements for non-thread-safe
2325 functions (like strtok(3) which uses a static internal buffer) or
2326 synchronous system functions (like gethostbyname(3) which doesn't
2327 provide an asynchronous mode where it doesn't block). When you want to
2328 use those functions in your server application together with threads,
2329 you've to either link the application against special third-party
2330 libraries (or for thread-safe/reentrant functions possibly against an
2331 existing C<libc_r> of the platform vendor). For an asynchronous DNS
2332 resolver library use the GNU B<adns> package from Ian Jackson ( see
2333 http://www.gnu.org/software/adns/adns.html ).
2334
2335 =head1 HISTORY
2336
2337 The B<Pth> library was designed and implemented between February and
2338 July 1999 by I<Ralf S. Engelschall> after evaluating numerous (mostly
2339 preemptive) thread libraries and after intensive discussions with
2340 I<Peter Simons>, I<Martin Kraemer>, I<Lars Eilebrecht> and I<Ralph
2341 Babel> related to an experimental (matrix based) non-preemptive C++
2342 scheduler class written by I<Peter Simons>.
2343
2344 B<Pth> was then implemented in order to combine the I<non-preemptive>
2345 approach of multithreading (which provides better portability and
2346 performance) with an API similar to the popular one found in B<Pthread>
2347 libraries (which provides easy programming).
2348
2349 So the essential idea of the non-preemptive approach was taken over from
2350 I<Peter Simons> scheduler. The priority based scheduling algorithm was
2351 suggested by I<Martin Kraemer>. Some code inspiration also came from
2352 an experimental threading library (B<rsthreads>) written by I<Robert
2353 S. Thau> for an ancient internal test version of the Apache webserver.
2354 The concept and API of message ports was borrowed from AmigaOS' B<Exec>
2355 subsystem. The concept and idea for the flexible event mechanism came
2356 from I<Paul Vixie>'s B<eventlib> (which can be found as a part of
2357 B<BIND> v8).
2358
2359 =head1 BUG REPORTS AND SUPPORT
2360
2361 If you think you have found a bug in B<Pth>, you should send a report as
2362 complete as possible to I<bug-pth@gnu.org>. If you can, please try to
2363 fix the problem and include a patch, made with 'C<diff -u3>', in your
2364 report. Always, at least, include a reasonable amount of description in
2365 your report to allow the author to deterministically reproduce the bug.
2366
2367 For further support you additionally can subscribe to the
2368 I<pth-users@gnu.org> mailing list by sending an Email to
2369 I<pth-users-request@gnu.org> with `C<subscribe pth-users>' (or
2370 `C<subscribe pth-users> I<address>' if you want to subscribe
2371 from a particular Email I<address>) in the body. Then you can
2372 discuss your issues with other B<Pth> users by sending messages to
2373 I<pth-users@gnu.org>. Currently (as of August 2000) you can reach about
2374 110 Pth users on this mailing list. Old postings you can find at
2375 I<http://www.mail-archive.com/pth-users@gnu.org/>.
2376
2377 =head1 SEE ALSO
2378
2379 =head2 Related Web Locations
2380
2381 `comp.programming.threads Newsgroup Archive',
2382 http://www.deja.com/topics_if.xp?
2383 search=topic&group=comp.programming.threads
2384
2385 `comp.programming.threads Frequently Asked Questions (F.A.Q.)',
2386 http://www.lambdacs.com/newsgroup/FAQ.html
2387
2388 `I<Multithreading - Definitions and Guidelines>',
2389 Numeric Quest Inc 1998;
2390 http://www.numeric-quest.com/lang/multi-frame.html
2391
2392 `I<The Single UNIX Specification, Version 2 - Threads>',
2393 The Open Group 1997;
2394 http://www.opengroup.org/onlinepubs /007908799/xsh/threads.html
2395
2396 SMI Thread Resources,
2397 Sun Microsystems Inc;
2398 http://www.sun.com/workshop/threads/
2399
2400 Bibliography on threads and multithreading,
2401 Torsten Amundsen;
2402 http://liinwww.ira.uka.de/bibliography/Os/threads.html
2403
2404 =head2 Related Books
2405
2406 B. Nichols, D. Buttlar, J.P. Farrel:
2407 `I<Pthreads Programming - A POSIX Standard for Better Multiprocessing>',
2408 O'Reilly 1996;
2409 ISBN 1-56592-115-1
2410
2411 B. Lewis, D. J. Berg:
2412 `I<Multithreaded Programming with Pthreads>',
2413 Sun Microsystems Press, Prentice Hall 1998;
2414 ISBN 0-13-680729-1
2415
2416 B. Lewis, D. J. Berg:
2417 `I<Threads Primer - A Guide To Multithreaded Programming>',
2418 Prentice Hall 1996;
2419 ISBN 0-13-443698-9
2420
2421 S. J. Norton, M. D. Dipasquale:
2422 `I<Thread Time - The Multithreaded Programming Guide>',
2423 Prentice Hall 1997;
2424 ISBN 0-13-190067-6
2425
2426 D. R. Butenhof:
2427 `I<Programming with POSIX Threads>',
2428 Addison Wesley 1997;
2429 ISBN 0-201-63392-2
2430
2431 =head2 Related Manpages
2432
2433 pth-config(1), pthread(3).
2434
2435 getcontext(2), setcontext(2), makecontext(2), swapcontext(2),
2436 sigstack(2), sigaltstack(2), sigaction(2), sigemptyset(2), sigaddset(2),
2437 sigprocmask(2), sigsuspend(2), sigsetjmp(3), siglongjmp(3), setjmp(3),
2438 longjmp(3), select(2), gettimeofday(2).
2439
2440 =head1 AUTHOR
2441
2442  Ralf S. Engelschall
2443  rse@engelschall.com
2444  www.engelschall.com
2445
2446 =cut
2447