# man > pth(3)

[pth(3)](https://www.chedong.com/phpMan.php/man/pth/3/markdown)                                  GNU Portable Threads                                  [pth(3)](https://www.chedong.com/phpMan.php/man/pth/3/markdown)



## NAME
       **pth** - GNU Portable Threads

## VERSION
       GNU Pth 2.0.7 (08-Jun-2006)

## SYNOPSIS
### Global Library Management
           pth_init, pth_kill, pth_ctrl, pth_version.

### Thread Attribute Handling
           pth_attr_of, pth_attr_new, pth_attr_init, pth_attr_set, pth_attr_get, pth_attr_destroy.

### Thread Control
           pth_spawn, pth_once, pth_self, pth_suspend, pth_resume, pth_yield, pth_nap, pth_wait,
           pth_cancel, pth_abort, pth_raise, pth_join, pth_exit.

### Utilities
           pth_fdmode, pth_time, pth_timeout, pth_sfiodisc.

### Cancellation Management
           pth_cancel_point, pth_cancel_state.

### Event Handling
           pth_event, pth_event_typeof, pth_event_extract, pth_event_concat, pth_event_isolate,
           pth_event_walk, pth_event_status, pth_event_free.

### Key-Based Storage
           pth_key_create, pth_key_delete, pth_key_setdata, pth_key_getdata.

### Message Port Communication
           pth_msgport_create, pth_msgport_destroy, pth_msgport_find, pth_msgport_pending, pth_msg‐
           port_put, pth_msgport_get, pth_msgport_reply.

### Thread Cleanups
           pth_cleanup_push, pth_cleanup_pop.

### Process Forking
           pth_atfork_push, pth_atfork_pop, pth_fork.

### Synchronization
           pth_mutex_init, pth_mutex_acquire, pth_mutex_release, pth_rwlock_init, pth_rwlock_ac‐
           quire, pth_rwlock_release, pth_cond_init, pth_cond_await, pth_cond_notify, pth_bar‐
           rier_init, pth_barrier_reach.

### User-Space Context
           pth_uctx_create, pth_uctx_make, pth_uctx_switch, pth_uctx_destroy.

### Generalized POSIX Replacement API
           pth_sigwait_ev, pth_accept_ev, pth_connect_ev, pth_select_ev, pth_poll_ev, pth_read_ev,
           pth_readv_ev, pth_write_ev, pth_writev_ev, pth_recv_ev, pth_recvfrom_ev, pth_send_ev,
           pth_sendto_ev.

### Standard POSIX Replacement API
           pth_nanosleep, pth_usleep, pth_sleep, pth_waitpid, pth_system, pth_sigmask, pth_sigwait,
           pth_accept, pth_connect, pth_select, pth_pselect, pth_poll, pth_read, pth_readv,
           pth_write, pth_writev, pth_pread, pth_pwrite, pth_recv, pth_recvfrom, pth_send,
           pth_sendto.

## DESCRIPTION
         ____  _   _
        ⎪  _ \⎪ ⎪_⎪ ⎪__
        ⎪ ⎪_) ⎪ __⎪ '_ \         ``Only those who attempt
        ⎪  __/⎪ ⎪_⎪ ⎪ ⎪ ⎪          the absurd can achieve
        ⎪_⎪    \__⎪_⎪ ⎪_⎪          the impossible.''

       **Pth** is a very portable POSIX/ANSI-C based library for Unix platforms which provides non-pre‐
       emptive priority-based scheduling for multiple threads of execution (aka `multithreading')
       inside event-driven applications. All threads run in the same address space of the applica‐
       tion process, but each thread has its own individual program counter, run-time stack, signal
       mask and "errno" variable.

       The thread scheduling itself is done in a cooperative way, i.e., the threads are managed and
       dispatched by a priority- and event-driven non-preemptive scheduler. The intention is that
       this way both better portability and run-time performance is achieved than with preemptive
       scheduling. The event facility allows threads to wait until various types of internal and ex‐
       ternal events occur, including pending I/O on file descriptors, asynchronous signals, elapsed
       timers, pending I/O on message ports, thread and process termination, and even results of
       customized callback functions.

       **Pth** also provides an optional emulation API for POSIX.1c threads (`Pthreads') which can be
       used for backward compatibility to existing multithreaded applications. See **Pth**'s [_pthread_(3)](https://www.chedong.com/phpMan.php/man/pthread/3/markdown)
       manual page for details.

### Threading Background

       When programming event-driven applications, usually servers, lots of regular jobs and one-
       shot requests have to be processed in parallel.  To efficiently simulate this parallel pro‐
       cessing on uniprocessor machines, we use `multitasking' -- that is, we have the application
       ask the operating system to spawn multiple instances of itself. On Unix, typically the kernel
       implements multitasking in a preemptive and priority-based way through heavy-weight processes
       spawned with [_fork_(2)](https://www.chedong.com/phpMan.php/man/fork/2/markdown).  These processes usually do _not_ share a common address space. Instead
       they are clearly separated from each other, and are created by direct cloning a process ad‐
       dress space (although modern kernels use memory segment mapping and copy-on-write semantics
       to avoid unnecessary copying of physical memory).

       The drawbacks are obvious: Sharing data between the processes is complicated, and can usually
       only be done efficiently through shared memory (but which itself is not very portable). Syn‐
       chronization is complicated because of the preemptive nature of the Unix scheduler (one has
       to use _atomic_ locks, etc). The machine's resources can be exhausted very quickly when the
       server application has to serve too many long-running requests (heavy-weight processes cost
       memory). And when each request spawns a sub-process to handle it, the server performance and
       responsiveness is horrible (heavy-weight processes cost time to spawn). Finally, the server
       application doesn't scale very well with the load because of these resource problems. In
       practice, lots of tricks are usually used to overcome these problems - ranging from pre-
       forked sub-process pools to semi-serialized processing, etc.

       One of the most elegant ways to solve these resource- and data-sharing problems is to have
       multiple _light-weight_ threads of execution inside a single (heavy-weight) process, i.e., to
       use _multithreading_.  Those _threads_ usually improve responsiveness and performance of the ap‐
       plication, often improve and simplify the internal program structure, and most important, re‐
       quire less system resources than heavy-weight processes. Threads are neither the optimal run-
       time facility for all types of applications, nor can all applications benefit from them. But
       at least event-driven server applications usually benefit greatly from using threads.

### The World of Threading

       Even though lots of documents exists which describe and define the world of threading, to un‐
       derstand **Pth**, you need only basic knowledge about threading. The following definitions of
       thread-related terms should at least help you understand thread programming enough to allow
       you to use **Pth**.

       **o** **process** vs. **thread**
         A process on Unix systems consists of at least the following fundamental ingredients: _vir__‐
         _tual_ _memory_ _table_, _program_ _code_, _program_ _counter_, _heap_ _memory_, _stack_ _memory_, _stack_ _pointer_,
         _file_ _descriptor_ _set_, _signal_ _table_. On every process switch, the kernel saves and restores
         these ingredients for the individual processes. On the other hand, a thread consists of
         only a private program counter, stack memory, stack pointer and signal table. All other in‐
         gredients, in particular the virtual memory, it shares with the other threads of the same
         process.

       **o** **kernel-space** vs. **user-space** threading
         Threads on a Unix platform traditionally can be implemented either inside kernel-space or
         user-space. When threads are implemented by the kernel, the thread context switches are
         performed by the kernel without the application's knowledge. Similarly, when threads are
         implemented in user-space, the thread context switches are performed by an application li‐
         brary, without the kernel's knowledge. There also are hybrid threading approaches where,
         typically, a user-space library binds one or more user-space threads to one or more kernel-
         space threads (there usually called light-weight processes - or in short LWPs).

         User-space threads are usually more portable and can perform faster and cheaper context
         switches (for instance via [_swapcontext_(2)](https://www.chedong.com/phpMan.php/man/swapcontext/2/markdown) or [_setjmp_(3)](https://www.chedong.com/phpMan.php/man/setjmp/3/markdown)/[_longjmp_(3)](https://www.chedong.com/phpMan.php/man/longjmp/3/markdown)) than kernel based
         threads. On the other hand, kernel-space threads can take advantage of multiprocessor ma‐
         chines and don't have any inherent I/O blocking problems. Kernel-space threads are usually
         scheduled in preemptive way side-by-side with the underlying processes. User-space threads
         on the other hand use either preemptive or non-preemptive scheduling.

       **o** **preemptive** vs. **non-preemptive** thread scheduling
         In preemptive scheduling, the scheduler lets a thread execute until a blocking situation
         occurs (usually a function call which would block) or the assigned timeslice elapses. Then
         it detracts control from the thread without a chance for the thread to object. This is usu‐
         ally realized by interrupting the thread through a hardware interrupt signal (for kernel-
         space threads) or a software interrupt signal (for user-space threads), like "SIGALRM" or
         "SIGVTALRM". In non-preemptive scheduling, once a thread received control from the sched‐
         uler it keeps it until either a blocking situation occurs (again a function call which
         would block and instead switches back to the scheduler) or the thread explicitly yields
         control back to the scheduler in a cooperative way.

       **o** **concurrency** vs. **parallelism**
         Concurrency exists when at least two threads are _in_ _progress_ at the same time. Parallelism
         arises when at least two threads are _executing_ simultaneously. Real parallelism can be only
         achieved on multiprocessor machines, of course. But one also usually speaks of parallelism
         or _high_ _concurrency_ in the context of preemptive thread scheduling and of _low_ _concurrency_
         in the context of non-preemptive thread scheduling.

### o responsiveness
         The responsiveness of a system can be described by the user visible delay until the system
         responses to an external request. When this delay is small enough and the user doesn't rec‐
         ognize a noticeable delay, the responsiveness of the system is considered good. When the
         user recognizes or is even annoyed by the delay, the responsiveness of the system is con‐
         sidered bad.

       **o** **reentrant**, **thread-safe** and **asynchronous-safe** functions
         A reentrant function is one that behaves correctly if it is called simultaneously by sev‐
         eral threads and then also executes simultaneously.  Functions that access global state,
         such as memory or files, of course, need to be carefully designed in order to be reentrant.
         Two traditional approaches to solve these problems are caller-supplied states and thread-
         specific data.

         Thread-safety is the avoidance of _data_ _races_, i.e., situations in which data is set to ei‐
         ther correct or incorrect value depending upon the (unpredictable) order in which multiple
         threads access and modify the data. So a function is thread-safe when it still behaves se‐
         mantically correct when called simultaneously by several threads (it is not required that
         the functions also execute simultaneously). The traditional approach to achieve thread-
         safety is to wrap a function body with an internal mutual exclusion lock (aka `mutex'). As
         you should recognize, reentrant is a stronger attribute than thread-safe, because it is
         harder to achieve and results especially in no run-time contention between threads. So, a
         reentrant function is always thread-safe, but not vice versa.

         Additionally there is a related attribute for functions named asynchronous-safe, which
         comes into play in conjunction with signal handlers. This is very related to the problem of
         reentrant functions. An asynchronous-safe function is one that can be called safe and with‐
         out side-effects from within a signal handler context. Usually very few functions are of
         this type, because an application is very restricted in what it can perform from within a
         signal handler (especially what system functions it is allowed to call). The reason mainly
         is, because only a few system functions are officially declared by POSIX as guaranteed to
         be asynchronous-safe. Asynchronous-safe functions usually have to be already reentrant.

### User-Space Threads

       User-space threads can be implemented in various way. The two traditional approaches are:

### 1. Matrix-based explicit dispatching between small units of execution:

          Here the global procedures of the application are split into small execution units (each
          is required to not run for more than a few milliseconds) and those units are implemented
          by separate functions.  Then a global matrix is defined which describes the execution (and
          perhaps even dependency) order of these functions. The main server procedure then just
          dispatches between these units by calling one function after each other controlled by this
          matrix. The threads are created by more than one jump-trail through this matrix and by
          switching between these jump-trails controlled by corresponding occurred events.

          This approach gives the best possible performance, because one can fine-tune the threads
          of execution by adjusting the matrix, and the scheduling is done explicitly by the appli‐
          cation itself. It is also very portable, because the matrix is just an ordinary data
          structure, and functions are a standard feature of ANSI C.

          The disadvantage of this approach is that it is complicated to write large applications
          with this approach, because in those applications one quickly gets hundreds(!) of execu‐
          tion units and the control flow inside such an application is very hard to understand (be‐
          cause it is interrupted by function borders and one always has to remember the global dis‐
          patching matrix to follow it). Additionally, all threads operate on the same execution
          stack. Although this saves memory, it is often nasty, because one cannot switch between
          threads in the middle of a function. Thus the scheduling borders are the function borders.

### 2. Context-based implicit scheduling between threads of execution:

          Here the idea is that one programs the application as with forked processes, i.e., one
          spawns a thread of execution and this runs from the begin to the end without an inter‐
          rupted control flow. But the control flow can be still interrupted - even in the middle of
          a function.  Actually in a preemptive way, similar to what the kernel does for the heavy-
          weight processes, i.e., every few milliseconds the user-space scheduler switches between
          the threads of execution. But the thread itself doesn't recognize this and usually (except
          for synchronization issues) doesn't have to care about this.

          The advantage of this approach is that it's very easy to program, because the control flow
          and context of a thread directly follows a procedure without forced interrupts through
          function borders.  Additionally, the programming is very similar to a traditional and well
          understood [_fork_(2)](https://www.chedong.com/phpMan.php/man/fork/2/markdown) based approach.

          The disadvantage is that although the general performance is increased, compared to using
          approaches based on heavy-weight processes, it is decreased compared to the matrix-ap‐
          proach above. Because the implicit preemptive scheduling does usually a lot more context
          switches (every user-space context switch costs some overhead even when it is a lot
          cheaper than a kernel-level context switch) than the explicit cooperative/non-preemptive
          scheduling.  Finally, there is no really portable POSIX/ANSI-C based way to implement
          user-space preemptive threading. Either the platform already has threads, or one has to
          hope that some semi-portable package exists for it. And even those semi-portable packages
          usually have to deal with assembler code and other nasty internals and are not easy to
          port to forthcoming platforms.

       So, in short: the matrix-dispatching approach is portable and fast, but nasty to program. The
       thread scheduling approach is easy to program, but suffers from synchronization and portabil‐
       ity problems caused by its preemptive nature.

### The Compromise of Pth

       But why not combine the good aspects of both approaches while avoiding their bad aspects?
       That's the goal of **Pth**. **Pth** implements easy-to-program threads of execution, but avoids the
       problems of preemptive scheduling by using non-preemptive scheduling instead.

       This sounds like, and is, a useful approach. Nevertheless, one has to keep the implications
       of non-preemptive thread scheduling in mind when working with **Pth**. The following list summa‐
       rizes a few essential points:

       **o** **Pth** **provides** **maximum** **portability,** **but** **NOT** **the** **fanciest** **features**.

         This is, because it uses a nifty and portable POSIX/ANSI-C approach for thread creation
         (and this way doesn't require any platform dependent assembler hacks) and schedules the
         threads in non-preemptive way (which doesn't require unportable facilities like "SIGV‐
         TALRM"). On the other hand, this way not all fancy threading features can be implemented.
         Nevertheless the available facilities are enough to provide a robust and full-featured
         threading system.

### o Pth increases the responsiveness and concurrency of an event-driven application, but NOT
         **the** **concurrency** **of** **number-crunching** **applications**.

         The reason is the non-preemptive scheduling. Number-crunching applications usually require
         preemptive scheduling to achieve concurrency because of their long CPU bursts. For them,
         non-preemptive scheduling (even together with explicit yielding) provides only the old con‐
         cept of `coroutines'. On the other hand, event driven applications benefit greatly from
         non-preemptive scheduling. They have only short CPU bursts and lots of events to wait on,
         and this way run faster under non-preemptive scheduling because no unnecessary context
         switching occurs, as it is the case for preemptive scheduling. That's why **Pth** is mainly in‐
         tended for server type applications, although there is no technical restriction.

       **o** **Pth** **requires** **thread-safe** **functions,** **but** **NOT** **reentrant** **functions**.

         This nice fact exists again because of the nature of non-preemptive scheduling, where a
         function isn't interrupted and this way cannot be reentered before it returned. This is a
         great portability benefit, because thread-safety can be achieved more easily than reen‐
         trance possibility. Especially this means that under **Pth** more existing third-party li‐
         braries can be used without side-effects than it's the case for other threading systems.

       **o** **Pth** **doesn't** **require** **any** **kernel** **support,** **but** **can** **NOT** **benefit** **from** **multiprocessor** **machines**.

         This means that **Pth** runs on almost all Unix kernels, because the kernel does not need to be
         aware of the **Pth** threads (because they are implemented entirely in user-space). On the
         other hand, it cannot benefit from the existence of multiprocessors, because for this, ker‐
         nel support would be needed. In practice, this is no problem, because multiprocessor sys‐
         tems are rare, and portability is almost more important than highest concurrency.

### The life cycle of a thread

       To understand the **Pth** Application Programming Interface (API), it helps to first understand
       the life cycle of a thread in the **Pth** threading system. It can be illustrated with the fol‐
       lowing directed graph:

                    NEW
                     ⎪
                     V
             +---> READY ---+
             ⎪       ^      ⎪
             ⎪       ⎪      V
          WAITING <--+-- RUNNING
                            ⎪
             :              V
          SUSPENDED       DEAD

       When a new thread is created, it is moved into the **NEW** queue of the scheduler. On the next
       dispatching for this thread, the scheduler picks it up from there and moves it to the **READY**
       queue. This is a queue containing all threads which want to perform a CPU burst. There they
       are queued in priority order. On each dispatching step, the scheduler always removes the
       thread with the highest priority only. It then increases the priority of all remaining
       threads by 1, to prevent them from `starving'.

       The thread which was removed from the **READY** queue is the new **RUNNING** thread (there is always
       just one **RUNNING** thread, of course). The **RUNNING** thread is assigned execution control. After
       this thread yields execution (either explicitly by yielding execution or implicitly by call‐
       ing a function which would block) there are three possibilities: Either it has terminated,
       then it is moved to the **DEAD** queue, or it has events on which it wants to wait, then it is
       moved into the **WAITING** queue. Else it is assumed it wants to perform more CPU bursts and im‐
       mediately enters the **READY** queue again.

       Before the next thread is taken out of the **READY** queue, the **WAITING** queue is checked for
       pending events. If one or more events occurred, the threads that are waiting on them are im‐
       mediately moved to the **READY** queue.

       The purpose of the **NEW** queue has to do with the fact that in **Pth** a thread never directly
       switches to another thread. A thread always yields execution to the scheduler and the sched‐
       uler dispatches to the next thread. So a freshly spawned thread has to be kept somewhere un‐
       til the scheduler gets a chance to pick it up for scheduling. That is what the **NEW** queue is
       for.

       The purpose of the **DEAD** queue is to support thread joining. When a thread is marked to be un‐
       joinable, it is directly kicked out of the system after it terminated. But when it is join‐
       able, it enters the **DEAD** queue. There it remains until another thread joins it.

       Finally, there is a special separated queue named **SUSPENDED**, to where threads can be manually
       moved from the **NEW**, **READY** or **WAITING** queues by the application. The purpose of this special
       queue is to temporarily absorb suspended threads until they are again resumed by the applica‐
       tion. Suspended threads do not cost scheduling or event handling resources, because they are
       temporarily completely out of the scheduler's scope. If a thread is resumed, it is moved back
       to the queue from where it originally came and this way again enters the schedulers scope.

### APPLICATION PROGRAMMING INTERFACE (API)
       In the following the **Pth** _Application_ _Programming_ _Interface_ (API) is discussed in detail. With
       the knowledge given above, it should now be easy to understand how to program threads with
       this API. In good Unix tradition, **Pth** functions use special return values ("NULL" in pointer
       context, "FALSE" in boolean context and "-1" in integer context) to indicate an error condi‐
       tion and set (or pass through) the "errno" system variable to pass more details about the er‐
       ror to the caller.

### Global Library Management

       The following functions act on the library as a whole.  They are used to initialize and shut‐
       down the scheduler and fetch information from it.

       int **pth**___**init**(void);
           This initializes the **Pth** library. It has to be the first **Pth** API function call in an ap‐
           plication, and is mandatory. It's usually done at the begin of the _main()_ function of the
           application. This implicitly spawns the internal scheduler thread and transforms the sin‐
           gle execution unit of the current process into a thread (the `main' thread). It returns
           "TRUE" on success and "FALSE" on error.

       int **pth**___**kill**(void);
           This kills the **Pth** library. It should be the last **Pth** API function call in an applica‐
           tion, but is not really required. It's usually done at the end of the main function of
           the application. At least, it has to be called from within the main thread. It implicitly
           kills all threads and transforms back the calling thread into the single execution unit
           of the underlying process.  The usual way to terminate a **Pth** application is either a sim‐
           ple `"[pth_exit(0)](https://www.chedong.com/phpMan.php/man/pthexit/0/markdown);"' in the main thread (which waits for all other threads to terminate,
           kills the threading system and then terminates the process) or a `"pth_kill(); [exit(0)](https://www.chedong.com/phpMan.php/man/exit/0/markdown)"'
           (which immediately kills the threading system and terminates the process). The _pth_kill()_
           return immediately with a return code of "FALSE" if it is not called from within the main
           thread. Else it kills the threading system and returns "TRUE".

       long **pth**___**ctrl**(unsigned long _query_, ...);
           This is a generalized query/control function for the **Pth** library.  The argument _query_ is
           a bitmask formed out of one or more "PTH_CTRL_"_XXXX_ queries. Currently the following
           queries are supported:

           "PTH_CTRL_GETTHREADS"
               This returns the total number of threads currently in existence.  This query actually
               is formed out of the combination of queries for threads in a particular state, i.e.,
               the "PTH_CTRL_GETTHREADS" query is equal to the OR-combination of all the following
               specialized queries:

               "PTH_CTRL_GETTHREADS_NEW" for the number of threads in the new queue (threads created
               via [_pth_spawn_(3)](https://www.chedong.com/phpMan.php/man/pthspawn/3/markdown) but still not scheduled once), "PTH_CTRL_GETTHREADS_READY" for the
               number of threads in the ready queue (threads who want to do CPU bursts),
               "PTH_CTRL_GETTHREADS_RUNNING" for the number of running threads (always just one
               thread!), "PTH_CTRL_GETTHREADS_WAITING" for the number of threads in the waiting
               queue (threads waiting for events), "PTH_CTRL_GETTHREADS_SUSPENDED" for the number of
               threads in the suspended queue (threads waiting to be resumed) and "PTH_CTRL_GET‐
               THREADS_DEAD" for the number of threads in the new queue (terminated threads waiting
               for a join).

           "PTH_CTRL_GETAVLOAD"
               This requires a second argument of type `"float *"' (pointer to a floating point
               variable).  It stores a floating point value describing the exponential averaged load
               of the scheduler in this variable. The load is a function from the number of threads
               in the ready queue of the schedulers dispatching unit.  So a load around 1.0 means
               there is only one ready thread (the standard situation when the application has no
               high load). A higher load value means there a more threads ready who want to do CPU
               bursts. The average load value updates once per second only. The return value for
               this query is always 0.

           "PTH_CTRL_GETPRIO"
               This requires a second argument of type `"pth_t"' which identifies a thread.  It re‐
               turns the priority (ranging from "PTH_PRIO_MIN" to "PTH_PRIO_MAX") of the given
               thread.

           "PTH_CTRL_GETNAME"
               This requires a second argument of type `"pth_t"' which identifies a thread. It re‐
               turns the name of the given thread, i.e., the return value of [_pth_ctrl_(3)](https://www.chedong.com/phpMan.php/man/pthctrl/3/markdown) should be
               casted to a `"char *"'.

           "PTH_CTRL_DUMPSTATE"
               This requires a second argument of type `"FILE *"' to which a summary of the internal
               **Pth** library state is written to. The main information which is currently written out
               is the current state of the thread pool.

           "PTH_CTRL_FAVOURNEW"
               This requires a second argument of type `"int"' which specified whether the **GNU** **Pth**
               scheduler favours new threads on startup, i.e., whether they are moved from the new
               queue to the top (argument is "TRUE") or middle (argument is "FALSE") of the ready
               queue. The default is to favour new threads to make sure they do not starve already
               at startup, although this slightly violates the strict priority based scheduling.

           The function returns "-1" on error.

       long **pth**___**version**(void);
           This function returns a hex-value `0x_VRRTLL_' which describes the current **Pth** library ver‐
           sion. _V_ is the version, _RR_ the revisions, _LL_ the level and _T_ the type of the level (al‐
           phalevel=0, betalevel=1, patchlevel=2, etc). For instance **Pth** version 1.0b1 is encoded as
           0x100101.  The reason for this unusual mapping is that this way the version number is
           steadily _increasing_. The same value is also available under compile time as "PTH_VER‐
           SION".

### Thread Attribute Handling

       Attribute objects are used in **Pth** for two things: First stand-alone/unbound attribute objects
       are used to store attributes for to be spawned threads.  Bounded attribute objects are used
       to modify attributes of already existing threads. The following attribute fields exists in
       attribute objects:

       "PTH_ATTR_PRIO" (read-write) ["int"]
           Thread Priority between "PTH_PRIO_MIN" and "PTH_PRIO_MAX".  The default is
           "PTH_PRIO_STD".

       "PTH_ATTR_NAME" (read-write) ["char *"]
           Name of thread (up to 40 characters are stored only), mainly for debugging purposes.

       "PTH_ATTR_DISPATCHES" (read-write) ["int"]
           In bounded attribute objects, this field is incremented every time the context is
           switched to the associated thread.

       "PTH_ATTR_JOINABLE" (read-write> ["int"]
           The thread detachment type, "TRUE" indicates a joinable thread, "FALSE" indicates a de‐
           tached thread. When a thread is detached, after termination it is immediately kicked out
           of the system instead of inserted into the dead queue.

       "PTH_ATTR_CANCEL_STATE" (read-write) ["unsigned int"]
           The thread cancellation state, i.e., a combination of "PTH_CANCEL_ENABLE" or "PTH_CAN‐
           CEL_DISABLE" and "PTH_CANCEL_DEFERRED" or "PTH_CANCEL_ASYNCHRONOUS".

       "PTH_ATTR_STACK_SIZE" (read-write) ["unsigned int"]
           The thread stack size in bytes. Use lower values than 64 KB with great care!

       "PTH_ATTR_STACK_ADDR" (read-write) ["char *"]
           A pointer to the lower address of a chunk of [_malloc_(3)](https://www.chedong.com/phpMan.php/man/malloc/3/markdown)'ed memory for the stack.

       "PTH_ATTR_TIME_SPAWN" (read-only) ["pth_time_t"]
           The time when the thread was spawned.  This can be queried only when the attribute object
           is bound to a thread.

       "PTH_ATTR_TIME_LAST" (read-only) ["pth_time_t"]
           The time when the thread was last dispatched.  This can be queried only when the attri‐
           bute object is bound to a thread.

       "PTH_ATTR_TIME_RAN" (read-only) ["pth_time_t"]
           The total time the thread was running.  This can be queried only when the attribute ob‐
           ject is bound to a thread.

       "PTH_ATTR_START_FUNC" (read-only) ["void *(*)(void *)"]
           The thread start function.  This can be queried only when the attribute object is bound
           to a thread.

       "PTH_ATTR_START_ARG" (read-only) ["void *"]
           The thread start argument.  This can be queried only when the attribute object is bound
           to a thread.

       "PTH_ATTR_STATE" (read-only) ["pth_state_t"]
           The scheduling state of the thread, i.e., either "PTH_STATE_NEW", "PTH_STATE_READY",
           "PTH_STATE_WAITING", or "PTH_STATE_DEAD" This can be queried only when the attribute ob‐
           ject is bound to a thread.

       "PTH_ATTR_EVENTS" (read-only) ["pth_event_t"]
           The event ring the thread is waiting for.  This can be queried only when the attribute
           object is bound to a thread.

       "PTH_ATTR_BOUND" (read-only) ["int"]
           Whether the attribute object is bound ("TRUE") to a thread or not ("FALSE").

       The following API functions can be used to handle the attribute objects:

       pth_attr_t **pth**___**attr**___**of**(pth_t _tid_);
           This returns a new attribute object _bound_ to thread _tid_.  Any queries on this object di‐
           rectly fetch attributes from _tid_. And attribute modifications directly change _tid_. Use
           such attribute objects to modify existing threads.

       pth_attr_t **pth**___**attr**___**new**(void);
           This returns a new _unbound_ attribute object. An implicit _pth_attr_init()_ is done on it.
           Any queries on this object just fetch stored attributes from it.  And attribute modifica‐
           tions just change the stored attributes.  Use such attribute objects to pre-configure at‐
           tributes for to be spawned threads.

       int **pth**___**attr**___**init**(pth_attr_t _attr_);
           This initializes an attribute object _attr_ to the default values: "PTH_ATTR_PRIO" :=
           "PTH_PRIO_STD", "PTH_ATTR_NAME" := `"unknown"', "PTH_ATTR_DISPATCHES" := 0,
           "PTH_ATTR_JOINABLE" := "TRUE", "PTH_ATTR_CANCELSTATE" := "PTH_CANCEL_DEFAULT",
           "PTH_ATTR_STACK_SIZE" := 64*1024 and "PTH_ATTR_STACK_ADDR" := "NULL". All other
           "PTH_ATTR_*" attributes are read-only attributes and don't receive default values in
           _attr_, because they exists only for bounded attribute objects.

       int **pth**___**attr**___**set**(pth_attr_t _attr_, int _field_, ...);
           This sets the attribute field _field_ in _attr_ to a value specified as an additional argu‐
           ment on the variable argument list. The following attribute _fields_ and argument pairs can
           be used:

            PTH_ATTR_PRIO           int
            PTH_ATTR_NAME           char *
            PTH_ATTR_DISPATCHES     int
            PTH_ATTR_JOINABLE       int
            PTH_ATTR_CANCEL_STATE   unsigned int
            PTH_ATTR_STACK_SIZE     unsigned int
            PTH_ATTR_STACK_ADDR     char *

       int **pth**___**attr**___**get**(pth_attr_t _attr_, int _field_, ...);
           This retrieves the attribute field _field_ in _attr_ and stores its value in the variable
           specified through a pointer in an additional argument on the variable argument list. The
           following _fields_ and argument pairs can be used:

            PTH_ATTR_PRIO           int *
            PTH_ATTR_NAME           char **
            PTH_ATTR_DISPATCHES     int *
            PTH_ATTR_JOINABLE       int *
            PTH_ATTR_CANCEL_STATE   unsigned int *
            PTH_ATTR_STACK_SIZE     unsigned int *
            PTH_ATTR_STACK_ADDR     char **
            PTH_ATTR_TIME_SPAWN     pth_time_t *
            PTH_ATTR_TIME_LAST      pth_time_t *
            PTH_ATTR_TIME_RAN       pth_time_t *
            PTH_ATTR_START_FUNC     void *(**)(void *)
            PTH_ATTR_START_ARG      void **
            PTH_ATTR_STATE          pth_state_t *
            PTH_ATTR_EVENTS         pth_event_t *
            PTH_ATTR_BOUND          int *

       int **pth**___**attr**___**destroy**(pth_attr_t _attr_);
           This destroys a attribute object _attr_. After this _attr_ is no longer a valid attribute ob‐
           ject.

### Thread Control

       The following functions control the threading itself and make up the main API of the **Pth** li‐
       brary.

       pth_t **pth**___**spawn**(pth_attr_t _attr_, void *(*_entry_)(void *), void *_arg_);
           This spawns a new thread with the attributes given in _attr_ (or "PTH_ATTR_DEFAULT" for de‐
           fault attributes - which means that thread priority, joinability and cancel state are in‐
           herited from the current thread) with the starting point at routine _entry_; the dispatch
           count is not inherited from the current thread if _attr_ is not specified - rather, it is
           initialized to zero.  This entry routine is called as `pth_exit(_entry_(_arg_))' inside the
           new thread unit, i.e., _entry_'s return value is fed to an implicit [_pth_exit_(3)](https://www.chedong.com/phpMan.php/man/pthexit/3/markdown). So the
           thread can also exit by just returning. Nevertheless the thread can also exit explicitly
           at any time by calling [_pth_exit_(3)](https://www.chedong.com/phpMan.php/man/pthexit/3/markdown). But keep in mind that calling the POSIX function
           [_exit_(3)](https://www.chedong.com/phpMan.php/man/exit/3/markdown) still terminates the complete process and not just the current thread.

           There is no **Pth**-internal limit on the number of threads one can spawn, except the limit
           implied by the available virtual memory. **Pth** internally keeps track of thread in dynamic
           data structures. The function returns "NULL" on error.

       int **pth**___**once**(pth_once_t *_ctrlvar_, void (*_func_)(void *), void *_arg_);
           This is a convenience function which uses a control variable of type "pth_once_t" to make
           sure a constructor function _func_ is called only once as `_func_(_arg_)' in the system. In
           other words: Only the first call to [_pth_once_(3)](https://www.chedong.com/phpMan.php/man/pthonce/3/markdown) by any thread in the system succeeds. The
           variable referenced via _ctrlvar_ should be declared as `"pth_once_t" _variable-name_ =
           "PTH_ONCE_INIT";' before calling this function.

       pth_t **pth**___**self**(void);
           This just returns the unique thread handle of the currently running thread.  This handle
           itself has to be treated as an opaque entity by the application.  It's usually used as an
           argument to other functions who require an argument of type "pth_t".

       int **pth**___**suspend**(pth_t _tid_);
           This suspends a thread _tid_ until it is manually resumed again via [_pth_resume_(3)](https://www.chedong.com/phpMan.php/man/pthresume/3/markdown). For
           this, the thread is moved to the **SUSPENDED** queue and this way is completely out of the
           scheduler's event handling and thread dispatching scope. Suspending the current thread is
           not allowed.  The function returns "TRUE" on success and "FALSE" on errors.

       int **pth**___**resume**(pth_t _tid_);
           This function resumes a previously suspended thread _tid_, i.e. _tid_ has to stay on the **SUS**‐‐
           **PENDED** queue. The thread is moved to the **NEW**, **READY** or **WAITING** queue (dependent on what
           its state was when the [_pth_suspend_(3)](https://www.chedong.com/phpMan.php/man/pthsuspend/3/markdown) call were made) and this way again enters the event
           handling and thread dispatching scope of the scheduler. The function returns "TRUE" on
           success and "FALSE" on errors.

       int **pth**___**raise**(pth_t _tid_, int _sig_)
           This function raises a signal for delivery to thread _tid_ only.  When one just raises a
           signal via [_raise_(3)](https://www.chedong.com/phpMan.php/man/raise/3/markdown) or [_kill_(2)](https://www.chedong.com/phpMan.php/man/kill/2/markdown), its delivered to an arbitrary thread which has this sig‐
           nal not blocked.  With [_pth_raise_(3)](https://www.chedong.com/phpMan.php/man/pthraise/3/markdown) one can send a signal to a thread and its guarantees
           that only this thread gets the signal delivered. But keep in mind that nevertheless the
           signals _action_ is still configured _process_-wide.  When _sig_ is 0 plain thread checking is
           performed, i.e., `"pth_raise(tid, 0)"' returns "TRUE" when thread _tid_ still exists in the
           **PTH** system but doesn't send any signal to it.

       int **pth**___**yield**(pth_t _tid_);
           This explicitly yields back the execution control to the scheduler thread.  Usually the
           execution is implicitly transferred back to the scheduler when a thread waits for an
           event. But when a thread has to do larger CPU bursts, it can be reasonable to interrupt
           it explicitly by doing a few [_pth_yield_(3)](https://www.chedong.com/phpMan.php/man/pthyield/3/markdown) calls to give other threads a chance to exe‐
           cute, too.  This obviously is the cooperating part of **Pth**.  A thread _has_ _not_ to yield ex‐
           ecution, of course. But when you want to program a server application with good response
           times the threads should be cooperative, i.e., when they should split their CPU bursts
           into smaller units with this call.

           Usually one specifies _tid_ as "NULL" to indicate to the scheduler that it can freely de‐
           cide which thread to dispatch next.  But if one wants to indicate to the scheduler that a
           particular thread should be favored on the next dispatching step, one can specify this
           thread explicitly. This allows the usage of the old concept of _coroutines_ where a
           thread/routine switches to a particular cooperating thread. If _tid_ is not "NULL" and
           points to a _new_ or _ready_ thread, it is guaranteed that this thread receives execution
           control on the next dispatching step. If _tid_ is in a different state (that is, not in
           "PTH_STATE_NEW" or "PTH_STATE_READY") an error is reported.

           The function usually returns "TRUE" for success and only "FALSE" (with "errno" set to
           "EINVAL") if _tid_ specified an invalid or still not new or ready thread.

       int **pth**___**nap**(pth_time_t _naptime_);
           This functions suspends the execution of the current thread until _naptime_ is elapsed.
           _naptime_ is of type "pth_time_t" and this way has theoretically a resolution of one mi‐
           crosecond. In practice you should neither rely on this nor that the thread is awakened
           exactly after _naptime_ has elapsed. It's only guarantees that the thread will sleep at
           least _naptime_. But because of the non-preemptive nature of **Pth** it can last longer (when
           another thread kept the CPU for a long time). Additionally the resolution is dependent of
           the implementation of timers by the operating system and these usually have only a reso‐
           lution of 10 microseconds or larger. But usually this isn't important for an application
           unless it tries to use this facility for real time tasks.

       int **pth**___**wait**(pth_event_t _ev_);
           This is the link between the scheduler and the event facility (see below for the various
           _pth_event_xxx()_ functions). It's modeled like [_select_(2)](https://www.chedong.com/phpMan.php/man/select/2/markdown), i.e., one gives this function
           one or more events (in the event ring specified by _ev_) on which the current thread wants
           to wait. The scheduler awakes the thread when one ore more of them occurred or failed af‐
           ter tagging them as such. The _ev_ argument is a _pointer_ to an event ring which isn't
           changed except for the tagging. [_pth_wait_(3)](https://www.chedong.com/phpMan.php/man/pthwait/3/markdown) returns the number of occurred or failed
           events and the application can use [_pth_event_status_(3)](https://www.chedong.com/phpMan.php/man/ptheventstatus/3/markdown) to test which events occurred or
           failed.

       int **pth**___**cancel**(pth_t _tid_);
           This cancels a thread _tid_. How the cancellation is done depends on the cancellation state
           of _tid_ which the thread can configure itself. When its state is "PTH_CANCEL_DISABLE" a
           cancellation request is just made pending.  When it is "PTH_CANCEL_ENABLE" it depends on
           the cancellation type what is performed. When its "PTH_CANCEL_DEFERRED" again the cancel‐
           lation request is just made pending. But when its "PTH_CANCEL_ASYNCHRONOUS" the thread is
           immediately canceled before [_pth_cancel_(3)](https://www.chedong.com/phpMan.php/man/pthcancel/3/markdown) returns. The effect of a thread cancellation is
           equal to implicitly forcing the thread to call `"pth_exit(PTH_CANCELED)"' at one of his
           cancellation points.  In **Pth** thread enter a cancellation point either explicitly via
           [_pth_cancel_point_(3)](https://www.chedong.com/phpMan.php/man/pthcancelpoint/3/markdown) or implicitly by waiting for an event.

       int **pth**___**abort**(pth_t _tid_);
           This is the cruel way to cancel a thread _tid_. When it's already dead and waits to be
           joined it just joins it (via `"pth_join("_tid_", NULL)"') and this way kicks it out of the
           system.  Else it forces the thread to be not joinable and to allow asynchronous cancella‐
           tion and then cancels it via `"pth_cancel("_tid_")"'.

       int **pth**___**join**(pth_t _tid_, void **_value_);
           This joins the current thread with the thread specified via _tid_.  It first suspends the
           current thread until the _tid_ thread has terminated. Then it is awakened and stores the
           value of _tid_'s [_pth_exit_(3)](https://www.chedong.com/phpMan.php/man/pthexit/3/markdown) call into *_value_ (if _value_ and not "NULL") and returns to the
           caller. A thread can be joined only when it has the attribute "PTH_ATTR_JOINABLE" set to
           "TRUE" (the default). A thread can only be joined once, i.e., after the [_pth_join_(3)](https://www.chedong.com/phpMan.php/man/pthjoin/3/markdown) call
           the thread _tid_ is completely removed from the system.

       void **pth**___**exit**(void *_value_);
           This terminates the current thread. Whether it's immediately removed from the system or
           inserted into the dead queue of the scheduler depends on its join type which was speci‐
           fied at spawning time. If it has the attribute "PTH_ATTR_JOINABLE" set to "FALSE", it's
           immediately removed and _value_ is ignored. Else the thread is inserted into the dead queue
           and _value_ remembered for a subsequent [_pth_join_(3)](https://www.chedong.com/phpMan.php/man/pthjoin/3/markdown) call by another thread.

### Utilities

       Utility functions.

       int **pth**___**fdmode**(int _fd_, int _mode_);
           This switches the non-blocking mode flag on file descriptor _fd_.  The argument _mode_ can be
           "PTH_FDMODE_BLOCK" for switching _fd_ into blocking I/O mode, "PTH_FDMODE_NONBLOCK" for
           switching _fd_ into non-blocking I/O mode or "PTH_FDMODE_POLL" for just polling the current
           mode. The current mode is returned (either "PTH_FDMODE_BLOCK" or "PTH_FDMODE_NONBLOCK")
           or "PTH_FDMODE_ERROR" on error. Keep in mind that since **Pth** 1.1 there is no longer a re‐
           quirement to manually switch a file descriptor into non-blocking mode in order to use it.
           This is automatically done temporarily inside **Pth**.  Instead when you now switch a file
           descriptor explicitly into non-blocking mode, [_pth_read_(3)](https://www.chedong.com/phpMan.php/man/pthread/3/markdown) or [_pth_write_(3)](https://www.chedong.com/phpMan.php/man/pthwrite/3/markdown) will never
           block the current thread.

       pth_time_t **pth**___**time**(long _sec_, long _usec_);
           This is a constructor for a "pth_time_t" structure which is a convenient function to
           avoid temporary structure values. It returns a _pth_time_t_ structure which holds the abso‐
           lute time value specified by _sec_ and _usec_.

       pth_time_t **pth**___**timeout**(long _sec_, long _usec_);
           This is a constructor for a "pth_time_t" structure which is a convenient function to
           avoid temporary structure values.  It returns a _pth_time_t_ structure which holds the ab‐
           solute time value calculated by adding _sec_ and _usec_ to the current time.

       Sfdisc_t ***pth**___**sfiodisc**(void);
           This functions is always available, but only reasonably usable when **Pth** was built with
           **Sfio** support ("--with-sfio" option) and "PTH_EXT_SFIO" is then defined by "pth.h". It is
           useful for applications which want to use the comprehensive **Sfio** I/O library with the **Pth**
           threading library. Then this function can be used to get an **Sfio** discipline structure
           ("Sfdisc_t") which can be pushed onto **Sfio** streams ("Sfio_t") in order to let this stream
           use [_pth_read_(3)](https://www.chedong.com/phpMan.php/man/pthread/3/markdown)/[_pth_write_(2)](https://www.chedong.com/phpMan.php/man/pthwrite/2/markdown) instead of [_read_(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown)/[_write_(2)](https://www.chedong.com/phpMan.php/man/write/2/markdown). The benefit is that this way
           I/O on the **Sfio** stream does only block the current thread instead of the whole process.
           The application has to [_free_(3)](https://www.chedong.com/phpMan.php/man/free/3/markdown) the "Sfdisc_t" structure when it is no longer needed. The
           Sfio package can be found at <http://www.research.att.com/sw/tools/sfio/>.

### Cancellation Management

       **Pth** supports POSIX style thread cancellation via [_pth_cancel_(3)](https://www.chedong.com/phpMan.php/man/pthcancel/3/markdown) and the following two related
       functions:

       void **pth**___**cancel**___**state**(int _newstate_, int *_oldstate_);
           This manages the cancellation state of the current thread.  When _oldstate_ is not "NULL"
           the function stores the old cancellation state under the variable pointed to by _oldstate_.
           When _newstate_ is not 0 it sets the new cancellation state. _oldstate_ is created before
           _newstate_ is set.  A state is a combination of "PTH_CANCEL_ENABLE" or "PTH_CANCEL_DISABLE"
           and "PTH_CANCEL_DEFERRED" or "PTH_CANCEL_ASYNCHRONOUS".  "PTH_CANCEL_ENABLE⎪PTH_CAN‐
           CEL_DEFERRED" (or "PTH_CANCEL_DEFAULT") is the default state where cancellation is possi‐
           ble but only at cancellation points.  Use "PTH_CANCEL_DISABLE" to complete disable can‐
           cellation for a thread and "PTH_CANCEL_ASYNCHRONOUS" for allowing asynchronous cancella‐
           tions, i.e., cancellations which can happen at any time.

       void **pth**___**cancel**___**point**(void);
           This explicitly enter a cancellation point. When the current cancellation state is
           "PTH_CANCEL_DISABLE" or no cancellation request is pending, this has no side-effect and
           returns immediately. Else it calls `"pth_exit(PTH_CANCELED)"'.

### Event Handling

       **Pth** has a very flexible event facility which is linked into the scheduler through the
       [_pth_wait_(3)](https://www.chedong.com/phpMan.php/man/pthwait/3/markdown) function. The following functions provide the handling of event rings.

       pth_event_t **pth**___**event**(unsigned long _spec_, ...);
           This creates a new event ring consisting of a single initial event.  The type of the gen‐
           erated event is specified by _spec_. The following types are available:

           "PTH_EVENT_FD"
               This is a file descriptor event. One or more of "PTH_UNTIL_FD_READABLE", "PTH_UN‐
               TIL_FD_WRITEABLE" or "PTH_UNTIL_FD_EXCEPTION" have to be OR-ed into _spec_ to specify
               on which state of the file descriptor you want to wait.  The file descriptor itself
               has to be given as an additional argument.  Example: `"pth_event(PTH_EVENT_FD⎪PTH_UN‐
               TIL_FD_READABLE, fd)"'.

           "PTH_EVENT_SELECT"
               This is a multiple file descriptor event modeled directly after the [_select_(2)](https://www.chedong.com/phpMan.php/man/select/2/markdown) call
               (actually it is also used to implement [_pth_select_(3)](https://www.chedong.com/phpMan.php/man/pthselect/3/markdown) internally).  It's a convenient
               way to wait for a large set of file descriptors at once and at each file descriptor
               for a different type of state. Additionally as a nice side-effect one receives the
               number of file descriptors which causes the event to be occurred (using BSD seman‐
               tics, i.e., when a file descriptor occurred in two sets it's counted twice). The ar‐
               guments correspond directly to the [_select_(2)](https://www.chedong.com/phpMan.php/man/select/2/markdown) function arguments except that there is
               no timeout argument (because timeouts already can be handled via "PTH_EVENT_TIME"
               events).

               Example: `"pth_event(PTH_EVENT_SELECT, &rc, nfd, rfds, wfds, efds)"' where "rc" has
               to be of type `"int *"', "nfd" has to be of type `"int"' and "rfds", "wfds" and
               "efds" have to be of type `"fd_set *"' (see [_select_(2)](https://www.chedong.com/phpMan.php/man/select/2/markdown)). The number of occurred file
               descriptors are stored in "rc".

           "PTH_EVENT_SIGS"
               This is a signal set event. The two additional arguments have to be a pointer to a
               signal set (type `"sigset_t *"') and a pointer to a signal number variable (type
               `"int *"').  This event waits until one of the signals in the signal set occurred.
               As a result the occurred signal number is stored in the second additional argument.
               Keep in mind that the **Pth** scheduler doesn't block signals automatically.  So when you
               want to wait for a signal with this event you've to block it via [_sigprocmask_(2)](https://www.chedong.com/phpMan.php/man/sigprocmask/2/markdown) or it
               will be delivered without your notice. Example: `"sigemptyset(&set); sigaddset(&set,
               SIGINT); pth_event(PTH_EVENT_SIG, &set, &sig);"'.

           "PTH_EVENT_TIME"
               This is a time point event. The additional argument has to be of type "pth_time_t"
               (usually on-the-fly generated via [_pth_time_(3)](https://www.chedong.com/phpMan.php/man/pthtime/3/markdown)). This events waits until the specified
               time point has elapsed. Keep in mind that the value is an absolute time point and not
               an offset. When you want to wait for a specified amount of time, you've to add the
               current time to the offset (usually on-the-fly achieved via [_pth_timeout_(3)](https://www.chedong.com/phpMan.php/man/pthtimeout/3/markdown)).  Exam‐
               ple: `"pth_event(PTH_EVENT_TIME, pth_timeout(2,0))"'.

           "PTH_EVENT_MSG"
               This is a message port event. The additional argument has to be of type "pth_msg‐
               port_t". This events waits until one or more messages were received on the specified
               message port.  Example: `"pth_event(PTH_EVENT_MSG, mp)"'.

           "PTH_EVENT_TID"
               This is a thread event. The additional argument has to be of type "pth_t".  One of
               "PTH_UNTIL_TID_NEW", "PTH_UNTIL_TID_READY", "PTH_UNTIL_TID_WAITING" or "PTH_UN‐
               TIL_TID_DEAD" has to be OR-ed into _spec_ to specify on which state of the thread you
               want to wait.  Example: `"pth_event(PTH_EVENT_TID⎪PTH_UNTIL_TID_DEAD, tid)"'.

           "PTH_EVENT_FUNC"
               This is a custom callback function event. Three additional arguments have to be given
               with the following types: `"int (*)(void *)"', `"void *"' and `"pth_time_t"'. The
               first is a function pointer to a check function and the second argument is a user-
               supplied context value which is passed to this function. The scheduler calls this
               function on a regular basis (on his own scheduler stack, so be very careful!) and the
               thread is kept sleeping while the function returns "FALSE". Once it returned "TRUE"
               the thread will be awakened. The check interval is defined by the third argument,
               i.e., the check function is polled again not until this amount of time elapsed. Exam‐
               ple: `"pth_event(PTH_EVENT_FUNC, func, arg, pth_time(0,500000))"'.

       unsigned long **pth**___**event**___**typeof**(pth_event_t _ev_);
           This returns the type of event _ev_. It's a combination of the describing "PTH_EVENT_XX"
           and "PTH_UNTIL_XX" value. This is especially useful to know which arguments have to be
           supplied to the [_pth_event_extract_(3)](https://www.chedong.com/phpMan.php/man/ptheventextract/3/markdown) function.

       int **pth**___**event**___**extract**(pth_event_t _ev_, ...);
           When [_pth_event_(3)](https://www.chedong.com/phpMan.php/man/pthevent/3/markdown) is treated like [_sprintf_(3)](https://www.chedong.com/phpMan.php/man/sprintf/3/markdown), then this function is [_sscanf_(3)](https://www.chedong.com/phpMan.php/man/sscanf/3/markdown), i.e., it
           is the inverse operation of [_pth_event_(3)](https://www.chedong.com/phpMan.php/man/pthevent/3/markdown). This means that it can be used to extract the
           ingredients of an event.  The ingredients are stored into variables which are given as
           pointers on the variable argument list.  Which pointers have to be present depends on the
           event type and has to be determined by the caller before via [_pth_event_typeof_(3)](https://www.chedong.com/phpMan.php/man/ptheventtypeof/3/markdown).

           To make it clear, when you constructed _ev_ via `"ev = pth_event(PTH_EVENT_FD, fd);"' you
           have to extract it via `"pth_event_extract(ev, &fd)"', etc. For multiple arguments of an
           event the order of the pointer arguments is the same as for [_pth_event_(3)](https://www.chedong.com/phpMan.php/man/pthevent/3/markdown). But always keep
           in mind that you have to always supply _pointers_ to _variables_ and these variables have to
           be of the same type as the argument of [_pth_event_(3)](https://www.chedong.com/phpMan.php/man/pthevent/3/markdown) required.

       pth_event_t **pth**___**event**___**concat**(pth_event_t _ev_, ...);
           This concatenates one or more additional event rings to the event ring _ev_ and returns _ev_.
           The end of the argument list has to be marked with a "NULL" argument. Use this function
           to create real events rings out of the single-event rings created by [_pth_event_(3)](https://www.chedong.com/phpMan.php/man/pthevent/3/markdown).

       pth_event_t **pth**___**event**___**isolate**(pth_event_t _ev_);
           This isolates the event _ev_ from possibly appended events in the event ring.  When in _ev_
           only one event exists, this returns "NULL". When remaining events exists, they form a new
           event ring which is returned.

       pth_event_t **pth**___**event**___**walk**(pth_event_t _ev_, int _direction_);
           This walks to the next (when _direction_ is "PTH_WALK_NEXT") or previews (when _direction_ is
           "PTH_WALK_PREV") event in the event ring _ev_ and returns this new reached event. Addition‐
           ally "PTH_UNTIL_OCCURRED" can be OR-ed into _direction_ to walk to the next/previous oc‐
           curred event in the ring _ev_.

       pth_status_t **pth**___**event**___**status**(pth_event_t _ev_);
           This returns the status of event _ev_. This is a fast operation because only a tag on _ev_ is
           checked which was either set or still not set by the scheduler. In other words: This
           doesn't check the event itself, it just checks the last knowledge of the scheduler. The
           possible returned status codes are: "PTH_STATUS_PENDING" (event is still pending),
           "PTH_STATUS_OCCURRED" (event successfully occurred), "PTH_STATUS_FAILED" (event failed).

       int **pth**___**event**___**free**(pth_event_t _ev_, int _mode_);
           This deallocates the event _ev_ (when _mode_ is "PTH_FREE_THIS") or all events appended to
           the event ring under _ev_ (when _mode_ is "PTH_FREE_ALL").

### Key-Based Storage

       The following functions provide thread-local storage through unique keys similar to the POSIX
       **Pthread** API. Use this for thread specific global data.

       int **pth**___**key**___**create**(pth_key_t *_key_, void (*_func_)(void *));
           This created a new unique key and stores it in _key_.  Additionally _func_ can specify a de‐
           structor function which is called on the current threads termination with the _key_.

       int **pth**___**key**___**delete**(pth_key_t _key_);
           This explicitly destroys a key _key_.

       int **pth**___**key**___**setdata**(pth_key_t _key_, const void *_value_);
           This stores _value_ under _key_.

       void ***pth**___**key**___**getdata**(pth_key_t _key_);
           This retrieves the value under _key_.

### Message Port Communication

       The following functions provide message ports which can be used for efficient and flexible
       inter-thread communication.

       pth_msgport_t **pth**___**msgport**___**create**(const char *_name_);
           This returns a pointer to a new message port. If name _name_ is not "NULL", the _name_ can be
           used by other threads via [_pth_msgport_find_(3)](https://www.chedong.com/phpMan.php/man/pthmsgportfind/3/markdown) to find the message port in case they do
           not know directly the pointer to the message port.

       void **pth**___**msgport**___**destroy**(pth_msgport_t _mp_);
           This destroys a message port _mp_. Before all pending messages on it are replied to their
           origin message port.

       pth_msgport_t **pth**___**msgport**___**find**(const char *_name_);
           This finds a message port in the system by _name_ and returns the pointer to it.

       int **pth**___**msgport**___**pending**(pth_msgport_t _mp_);
           This returns the number of pending messages on message port _mp_.

       int **pth**___**msgport**___**put**(pth_msgport_t _mp_, pth_message_t *_m_);
           This puts (or sends) a message _m_ to message port _mp_.

       pth_message_t ***pth**___**msgport**___**get**(pth_msgport_t _mp_);
           This gets (or receives) the top message from message port _mp_.  Incoming messages are al‐
           ways kept in a queue, so there can be more pending messages, of course.

       int **pth**___**msgport**___**reply**(pth_message_t *_m_);
           This replies a message _m_ to the message port of the sender.

### Thread Cleanups

       Per-thread cleanup functions.

       int **pth**___**cleanup**___**push**(void (*_handler_)(void *), void *_arg_);
           This pushes the routine _handler_ onto the stack of cleanup routines for the current
           thread.  These routines are called in LIFO order when the thread terminates.

       int **pth**___**cleanup**___**pop**(int _execute_);
           This pops the top-most routine from the stack of cleanup routines for the current thread.
           When _execute_ is "TRUE" the routine is additionally called.

### Process Forking

       The following functions provide some special support for process forking situations inside
       the threading environment.

       int **pth**___**atfork**___**push**(void (*_prepare_)(void *), void (*)(void *_parent_), void (*)(void *_child_),
       void *_arg_);
           This function declares forking handlers to be called before and after [_pth_fork_(3)](https://www.chedong.com/phpMan.php/man/pthfork/3/markdown), in the
           context of the thread that called [_pth_fork_(3)](https://www.chedong.com/phpMan.php/man/pthfork/3/markdown). The _prepare_ handler is called before
           [_fork_(2)](https://www.chedong.com/phpMan.php/man/fork/2/markdown) processing commences. The _parent_ handler is called   after [_fork_(2)](https://www.chedong.com/phpMan.php/man/fork/2/markdown) processing
           completes in the parent process.  The _child_ handler is called after [_fork_(2)](https://www.chedong.com/phpMan.php/man/fork/2/markdown) processing
           completed in the child process. If no handling is desired at one or more of these three
           points, the corresponding handler can be given as "NULL".  Each handler is called with
           _arg_ as the argument.

           The order of calls to [_pth_atfork_push_(3)](https://www.chedong.com/phpMan.php/man/pthatforkpush/3/markdown) is significant. The _parent_ and _child_ handlers
           are called in the order in which they were established by calls to [_pth_atfork_push_(3)](https://www.chedong.com/phpMan.php/man/pthatforkpush/3/markdown),
           i.e., FIFO. The _prepare_ fork handlers are called in the opposite order, i.e., LIFO.

       int **pth**___**atfork**___**pop**(void);
           This removes the top-most handlers on the forking handler stack which were established
           with the last [_pth_atfork_push_(3)](https://www.chedong.com/phpMan.php/man/pthatforkpush/3/markdown) call. It returns "FALSE" when no more handlers couldn't
           be removed from the stack.

       pid_t **pth**___**fork**(void);
           This is a variant of [_fork_(2)](https://www.chedong.com/phpMan.php/man/fork/2/markdown) with the difference that the current thread only is forked
           into a separate process, i.e., in the parent process nothing changes while in the child
           process all threads are gone except for the scheduler and the calling thread. When you
           really want to duplicate all threads in the current process you should use [_fork_(2)](https://www.chedong.com/phpMan.php/man/fork/2/markdown) di‐
           rectly. But this is usually not reasonable. Additionally this function takes care of
           forking handlers as established by [_pth_fork_push_(3)](https://www.chedong.com/phpMan.php/man/pthforkpush/3/markdown).

### Synchronization

       The following functions provide synchronization support via mutual exclusion locks (**mutex**),
       read-write locks (**rwlock**), condition variables (**cond**) and barriers (**barrier**). Keep in mind
       that in a non-preemptive threading system like **Pth** this might sound unnecessary at the first
       look, because a thread isn't interrupted by the system. Actually when you have a critical
       code section which doesn't contain any _pth_xxx()_ functions, you don't need any mutex to pro‐
       tect it, of course.

       But when your critical code section contains any _pth_xxx()_ function the chance is high that
       these temporarily switch to the scheduler. And this way other threads can make progress and
       enter your critical code section, too.  This is especially true for critical code sections
       which implicitly or explicitly use the event mechanism.

       int **pth**___**mutex**___**init**(pth_mutex_t *_mutex_);
           This dynamically initializes a mutex variable of type `"pth_mutex_t"'.  Alternatively one
           can also use static initialization via `"pth_mutex_t mutex = PTH_MUTEX_INIT"'.

       int **pth**___**mutex**___**acquire**(pth_mutex_t *_mutex_, int _try_, pth_event_t _ev_);
           This acquires a mutex _mutex_.  If the mutex is already locked by another thread, the cur‐
           rent threads execution is suspended until the mutex is unlocked again or additionally the
           extra events in _ev_ occurred (when _ev_ is not "NULL").  Recursive locking is explicitly
           supported, i.e., a thread is allowed to acquire a mutex more than once before its re‐
           leased. But it then also has be released the same number of times until the mutex is
           again lockable by others.  When _try_ is "TRUE" this function never suspends execution. In‐
           stead it returns "FALSE" with "errno" set to "EBUSY".

       int **pth**___**mutex**___**release**(pth_mutex_t *_mutex_);
           This decrements the recursion locking count on _mutex_ and when it is zero it releases the
           mutex _mutex_.

       int **pth**___**rwlock**___**init**(pth_rwlock_t *_rwlock_);
           This dynamically initializes a read-write lock variable of type `"pth_rwlock_t"'.  Alter‐
           natively one can also use static initialization via `"pth_rwlock_t rwlock =
           PTH_RWLOCK_INIT"'.

       int **pth**___**rwlock**___**acquire**(pth_rwlock_t *_rwlock_, int _op_, int _try_, pth_event_t _ev_);
           This acquires a read-only (when _op_ is "PTH_RWLOCK_RD") or a read-write (when _op_ is
           "PTH_RWLOCK_RW") lock _rwlock_. When the lock is only locked by other threads in read-only
           mode, the lock succeeds.  But when one thread holds a read-write lock, all locking at‐
           tempts suspend the current thread until this lock is released again. Additionally in _ev_
           events can be given to let the locking timeout, etc. When _try_ is "TRUE" this function
           never suspends execution. Instead it returns "FALSE" with "errno" set to "EBUSY".

       int **pth**___**rwlock**___**release**(pth_rwlock_t *_rwlock_);
           This releases a previously acquired (read-only or read-write) lock.

       int **pth**___**cond**___**init**(pth_cond_t *_cond_);
           This dynamically initializes a condition variable variable of type `"pth_cond_t"'.  Al‐
           ternatively one can also use static initialization via `"pth_cond_t cond =
           PTH_COND_INIT"'.

       int **pth**___**cond**___**await**(pth_cond_t *_cond_, pth_mutex_t *_mutex_, pth_event_t _ev_);
           This awaits a condition situation. The caller has to follow the semantics of the POSIX
           condition variables: _mutex_ has to be acquired before this function is called. The execu‐
           tion of the current thread is then suspended either until the events in _ev_ occurred (when
           _ev_ is not "NULL") or _cond_ was notified by another thread via [_pth_cond_notify_(3)](https://www.chedong.com/phpMan.php/man/pthcondnotify/3/markdown).  While
           the thread is waiting, _mutex_ is released. Before it returns _mutex_ is reacquired.

       int **pth**___**cond**___**notify**(pth_cond_t *_cond_, int _broadcast_);
           This notified one or all threads which are waiting on _cond_.  When _broadcast_ is "TRUE" all
           thread are notified, else only a single (unspecified) one.

       int **pth**___**barrier**___**init**(pth_barrier_t *_barrier_, int _threshold_);
           This dynamically initializes a barrier variable of type `"pth_barrier_t"'.  Alternatively
           one can also use static initialization via `"pth_barrier_t barrier = PTH_BAR‐
           RIER_INIT("_threadhold_")"'.

       int **pth**___**barrier**___**reach**(pth_barrier_t *_barrier_);
           This function reaches a barrier _barrier_. If this is the last thread (as specified by
           _threshold_ on init of _barrier_) all threads are awakened.  Else the current thread is sus‐
           pended until the last thread reached the barrier and this way awakes all threads. The
           function returns (beside "FALSE" on error) the value "TRUE" for any thread which neither
           reached the barrier as the first nor the last thread; "PTH_BARRIER_HEADLIGHT" for the
           thread which reached the barrier as the first thread and "PTH_BARRIER_TAILLIGHT" for the
           thread which reached the barrier as the last thread.

### User-Space Context

       The following functions provide a stand-alone sub-API for user-space context switching. It
       internally is based on the same underlying machine context switching mechanism the threads in
       **GNU** **Pth** are based on.  Hence these functions you can use for implementing your own simple
       user-space threads. The "pth_uctx_t" context is somewhat modeled after POSIX [_ucontext_(3)](https://www.chedong.com/phpMan.php/man/ucontext/3/markdown).

       The time required to create (via [_pth_uctx_make_(3)](https://www.chedong.com/phpMan.php/man/pthuctxmake/3/markdown)) a user-space context can range from just a
       few microseconds up to a more dramatical time (depending on the machine context switching
       method which is available on the platform). On the other hand, the raw performance in switch‐
       ing the user-space contexts is always very good (nearly independent of the used machine con‐
       text switching method). For instance, on an Intel Pentium-III CPU with 800Mhz running under
       FreeBSD 4 one usually achieves about 260,000 user-space context switches (via
       [_pth_uctx_switch_(3)](https://www.chedong.com/phpMan.php/man/pthuctxswitch/3/markdown)) per second.

       int **pth**___**uctx**___**create**(pth_uctx_t *_uctx_);
           This function creates a user-space context and stores it into _uctx_.  There is still no
           underlying user-space context configured. You still have to do this with
           [_pth_uctx_make_(3)](https://www.chedong.com/phpMan.php/man/pthuctxmake/3/markdown). On success, this function returns "TRUE", else "FALSE".

       int **pth**___**uctx**___**make**(pth_uctx_t _uctx_, char *_sk_addr_, size_t _sk_size_, const sigset_t *_sigmask_,
       void (*_start_func_)(void *), void *_start_arg_, pth_uctx_t _uctx_after_);
           This function makes a new user-space context in _uctx_ which will operate on the run-time
           stack _sk_addr_ (which is of maximum size _sk_size_), with the signals in _sigmask_ blocked (if
           _sigmask_ is not "NULL") and starting to execute with the call _start_func_(_start_arg_). If
           _sk_addr_ is "NULL", a stack is dynamically allocated. The stack size _sk_size_ has to be at
           least 16384 (16KB). If the start function _start_func_ returns and _uctx_after_ is not
           "NULL", an implicit user-space context switch to this context is performed. Else (if
           _uctx_after_ is "NULL") the process is terminated with [_exit_(3)](https://www.chedong.com/phpMan.php/man/exit/3/markdown). This function is somewhat
           modeled after POSIX [_makecontext_(3)](https://www.chedong.com/phpMan.php/man/makecontext/3/markdown). On success, this function returns "TRUE", else
           "FALSE".

       int **pth**___**uctx**___**switch**(pth_uctx_t _uctx_from_, pth_uctx_t _uctx_to_);
           This function saves the current user-space context in _uctx_from_ for later restoring by
           another call to [_pth_uctx_switch_(3)](https://www.chedong.com/phpMan.php/man/pthuctxswitch/3/markdown) and restores the new user-space context from _uctx_to_,
           which previously had to be set with either a previous call to [_pth_uctx_switch_(3)](https://www.chedong.com/phpMan.php/man/pthuctxswitch/3/markdown) or ini‐
           tially by [_pth_uctx_make_(3)](https://www.chedong.com/phpMan.php/man/pthuctxmake/3/markdown). This function is somewhat modeled after POSIX [_swapcontext_(3)](https://www.chedong.com/phpMan.php/man/swapcontext/3/markdown).
           If _uctx_from_ or _uctx_to_ are "NULL" or if _uctx_to_ contains no valid user-space context,
           "FALSE" is returned instead of "TRUE". These are the only errors possible.

       int **pth**___**uctx**___**destroy**(pth_uctx_t _uctx_);
           This function destroys the user-space context in _uctx_. The run-time stack associated with
           the user-space context is deallocated only if it was not given by the application (see
           _sk_addr_ of [_pth_uctx_create_(3)](https://www.chedong.com/phpMan.php/man/pthuctxcreate/3/markdown)).  If _uctx_ is "NULL", "FALSE" is returned instead of
           "TRUE". This is the only error possible.

### Generalized POSIX Replacement API

       The following functions are generalized replacements functions for the POSIX API, i.e., they
       are similar to the functions under `**Standard** **POSIX** **Replacement** **API**' but all have an addi‐
       tional event argument which can be used for timeouts, etc.

       int **pth**___**sigwait**___**ev**(const sigset_t *_set_, int *_sig_, pth_event_t _ev_);
           This is equal to [_pth_sigwait_(3)](https://www.chedong.com/phpMan.php/man/pthsigwait/3/markdown) (see below), but has an additional event argument _ev_.
           When [_pth_sigwait_(3)](https://www.chedong.com/phpMan.php/man/pthsigwait/3/markdown) suspends the current threads execution it usually only uses the sig‐
           nal event on _set_ to awake. With this function any number of extra events can be used to
           awake the current thread (remember that _ev_ actually is an event _ring_).

       int **pth**___**connect**___**ev**(int _s_, const struct sockaddr *_addr_, socklen_t _addrlen_, pth_event_t _ev_);
           This is equal to [_pth_connect_(3)](https://www.chedong.com/phpMan.php/man/pthconnect/3/markdown) (see below), but has an additional event argument _ev_.
           When [_pth_connect_(3)](https://www.chedong.com/phpMan.php/man/pthconnect/3/markdown) suspends the current threads execution it usually only uses the I/O
           event on _s_ to awake. With this function any number of extra events can be used to awake
           the current thread (remember that _ev_ actually is an event _ring_).

       int **pth**___**accept**___**ev**(int _s_, struct sockaddr *_addr_, socklen_t *_addrlen_, pth_event_t _ev_);
           This is equal to [_pth_accept_(3)](https://www.chedong.com/phpMan.php/man/pthaccept/3/markdown) (see below), but has an additional event argument _ev_. When
           [_pth_accept_(3)](https://www.chedong.com/phpMan.php/man/pthaccept/3/markdown) suspends the current threads execution it usually only uses the I/O event
           on _s_ to awake. With this function any number of extra events can be used to awake the
           current thread (remember that _ev_ actually is an event _ring_).

       int **pth**___**select**___**ev**(int _nfd_, fd_set *_rfds_, fd_set *_wfds_, fd_set *_efds_, struct timeval *_timeout_,
       pth_event_t _ev_);
           This is equal to [_pth_select_(3)](https://www.chedong.com/phpMan.php/man/pthselect/3/markdown) (see below), but has an additional event argument _ev_. When
           [_pth_select_(3)](https://www.chedong.com/phpMan.php/man/pthselect/3/markdown) suspends the current threads execution it usually only uses the I/O event
           on _rfds_, _wfds_ and _efds_ to awake. With this function any number of extra events can be
           used to awake the current thread (remember that _ev_ actually is an event _ring_).

       int **pth**___**poll**___**ev**(struct pollfd *_fds_, unsigned int _nfd_, int _timeout_, pth_event_t _ev_);
           This is equal to [_pth_poll_(3)](https://www.chedong.com/phpMan.php/man/pthpoll/3/markdown) (see below), but has an additional event argument _ev_. When
           [_pth_poll_(3)](https://www.chedong.com/phpMan.php/man/pthpoll/3/markdown) suspends the current threads execution it usually only uses the I/O event on
           _fds_ to awake. With this function any number of extra events can be used to awake the cur‐
           rent thread (remember that _ev_ actually is an event _ring_).

       ssize_t **pth**___**read**___**ev**(int _fd_, void *_buf_, size_t _nbytes_, pth_event_t _ev_);
           This is equal to [_pth_read_(3)](https://www.chedong.com/phpMan.php/man/pthread/3/markdown) (see below), but has an additional event argument _ev_. When
           [_pth_read_(3)](https://www.chedong.com/phpMan.php/man/pthread/3/markdown) suspends the current threads execution it usually only uses the I/O event on
           _fd_ to awake. With this function any number of extra events can be used to awake the cur‐
           rent thread (remember that _ev_ actually is an event _ring_).

       ssize_t **pth**___**readv**___**ev**(int _fd_, const struct iovec *_iovec_, int _iovcnt_, pth_event_t _ev_);
           This is equal to [_pth_readv_(3)](https://www.chedong.com/phpMan.php/man/pthreadv/3/markdown) (see below), but has an additional event argument _ev_. When
           [_pth_readv_(3)](https://www.chedong.com/phpMan.php/man/pthreadv/3/markdown) suspends the current threads execution it usually only uses the I/O event on
           _fd_ to awake. With this function any number of extra events can be used to awake the cur‐
           rent thread (remember that _ev_ actually is an event _ring_).

       ssize_t **pth**___**write**___**ev**(int _fd_, const void *_buf_, size_t _nbytes_, pth_event_t _ev_);
           This is equal to [_pth_write_(3)](https://www.chedong.com/phpMan.php/man/pthwrite/3/markdown) (see below), but has an additional event argument _ev_. When
           [_pth_write_(3)](https://www.chedong.com/phpMan.php/man/pthwrite/3/markdown) suspends the current threads execution it usually only uses the I/O event on
           _fd_ to awake. With this function any number of extra events can be used to awake the cur‐
           rent thread (remember that _ev_ actually is an event _ring_).

       ssize_t **pth**___**writev**___**ev**(int _fd_, const struct iovec *_iovec_, int _iovcnt_, pth_event_t _ev_);
           This is equal to [_pth_writev_(3)](https://www.chedong.com/phpMan.php/man/pthwritev/3/markdown) (see below), but has an additional event argument _ev_. When
           [_pth_writev_(3)](https://www.chedong.com/phpMan.php/man/pthwritev/3/markdown) suspends the current threads execution it usually only uses the I/O event
           on _fd_ to awake. With this function any number of extra events can be used to awake the
           current thread (remember that _ev_ actually is an event _ring_).

       ssize_t **pth**___**recv**___**ev**(int _fd_, void *_buf_, size_t _nbytes_, int _flags_, pth_event_t _ev_);
           This is equal to [_pth_recv_(3)](https://www.chedong.com/phpMan.php/man/pthrecv/3/markdown) (see below), but has an additional event argument _ev_. When
           [_pth_recv_(3)](https://www.chedong.com/phpMan.php/man/pthrecv/3/markdown) suspends the current threads execution it usually only uses the I/O event on
           _fd_ to awake. With this function any number of extra events can be used to awake the cur‐
           rent thread (remember that _ev_ actually is an event _ring_).

       ssize_t **pth**___**recvfrom**___**ev**(int _fd_, void *_buf_, size_t _nbytes_, int _flags_, struct sockaddr *_from_,
       socklen_t *_fromlen_, pth_event_t _ev_);
           This is equal to [_pth_recvfrom_(3)](https://www.chedong.com/phpMan.php/man/pthrecvfrom/3/markdown) (see below), but has an additional event argument _ev_.
           When [_pth_recvfrom_(3)](https://www.chedong.com/phpMan.php/man/pthrecvfrom/3/markdown) suspends the current threads execution it usually only uses the I/O
           event on _fd_ to awake. With this function any number of extra events can be used to awake
           the current thread (remember that _ev_ actually is an event _ring_).

       ssize_t **pth**___**send**___**ev**(int _fd_, const void *_buf_, size_t _nbytes_, int _flags_, pth_event_t _ev_);
           This is equal to [_pth_send_(3)](https://www.chedong.com/phpMan.php/man/pthsend/3/markdown) (see below), but has an additional event argument _ev_. When
           [_pth_send_(3)](https://www.chedong.com/phpMan.php/man/pthsend/3/markdown) suspends the current threads execution it usually only uses the I/O event on
           _fd_ to awake. With this function any number of extra events can be used to awake the cur‐
           rent thread (remember that _ev_ actually is an event _ring_).

       ssize_t **pth**___**sendto**___**ev**(int _fd_, const void *_buf_, size_t _nbytes_, int _flags_, const struct sock‐
       addr *_to_, socklen_t _tolen_, pth_event_t _ev_);
           This is equal to [_pth_sendto_(3)](https://www.chedong.com/phpMan.php/man/pthsendto/3/markdown) (see below), but has an additional event argument _ev_. When
           [_pth_sendto_(3)](https://www.chedong.com/phpMan.php/man/pthsendto/3/markdown) suspends the current threads execution it usually only uses the I/O event
           on _fd_ to awake. With this function any number of extra events can be used to awake the
           current thread (remember that _ev_ actually is an event _ring_).

### Standard POSIX Replacement API

       The following functions are standard replacements functions for the POSIX API.  The differ‐
       ence is mainly that they suspend the current thread only instead of the whole process in case
       the file descriptors will block.

       int **pth**___**nanosleep**(const struct timespec *_rqtp_, struct timespec *_rmtp_);
           This is a variant of the POSIX [_nanosleep_(3)](https://www.chedong.com/phpMan.php/man/nanosleep/3/markdown) function. It suspends the current threads ex‐
           ecution until the amount of time in _rqtp_ elapsed.  The thread is guaranteed to not wake
           up before this time, but because of the non-preemptive scheduling nature of **Pth**, it can
           be awakened later, of course. If _rmtp_ is not "NULL", the "timespec" structure it refer‐
           ences is updated to contain the unslept amount (the request time minus the time actually
           slept time). The difference between [_nanosleep_(3)](https://www.chedong.com/phpMan.php/man/nanosleep/3/markdown) and [_pth_nanosleep_(3)](https://www.chedong.com/phpMan.php/man/pthnanosleep/3/markdown) is that that
           [_pth_nanosleep_(3)](https://www.chedong.com/phpMan.php/man/pthnanosleep/3/markdown) suspends only the execution of the current thread and not the whole
           process.

       int **pth**___**usleep**(unsigned int _usec_);
           This is a variant of the 4.3BSD [_usleep_(3)](https://www.chedong.com/phpMan.php/man/usleep/3/markdown) function. It suspends the current threads exe‐
           cution until _usec_ microseconds (= _usec_*1/1000000 sec) elapsed.  The thread is guaranteed
           to not wake up before this time, but because of the non-preemptive scheduling nature of
           **Pth**, it can be awakened later, of course.  The difference between [_usleep_(3)](https://www.chedong.com/phpMan.php/man/usleep/3/markdown) and
           [_pth_usleep_(3)](https://www.chedong.com/phpMan.php/man/pthusleep/3/markdown) is that that [_pth_usleep_(3)](https://www.chedong.com/phpMan.php/man/pthusleep/3/markdown) suspends only the execution of the current
           thread and not the whole process.

       unsigned int **pth**___**sleep**(unsigned int _sec_);
           This is a variant of the POSIX [_sleep_(3)](https://www.chedong.com/phpMan.php/man/sleep/3/markdown) function. It suspends the current threads execu‐
           tion until _sec_ seconds elapsed.  The thread is guaranteed to not wake up before this
           time, but because of the non-preemptive scheduling nature of **Pth**, it can be awakened
           later, of course.  The difference between [_sleep_(3)](https://www.chedong.com/phpMan.php/man/sleep/3/markdown) and [_pth_sleep_(3)](https://www.chedong.com/phpMan.php/man/pthsleep/3/markdown) is that [_pth_sleep_(3)](https://www.chedong.com/phpMan.php/man/pthsleep/3/markdown)
           suspends only the execution of the current thread and not the whole process.

       pid_t **pth**___**waitpid**(pid_t _pid_, int *_status_, int _options_);
           This is a variant of the POSIX [_waitpid_(2)](https://www.chedong.com/phpMan.php/man/waitpid/2/markdown) function. It suspends the current threads exe‐
           cution until _status_ information is available for a terminated child process _pid_.  The
           difference between [_waitpid_(2)](https://www.chedong.com/phpMan.php/man/waitpid/2/markdown) and [_pth_waitpid_(3)](https://www.chedong.com/phpMan.php/man/pthwaitpid/3/markdown) is that [_pth_waitpid_(3)](https://www.chedong.com/phpMan.php/man/pthwaitpid/3/markdown) suspends only the
           execution of the current thread and not the whole process.  For more details about the
           arguments and return code semantics see [_waitpid_(2)](https://www.chedong.com/phpMan.php/man/waitpid/2/markdown).

       int **pth**___**system**(const char *_cmd_);
           This is a variant of the POSIX [_system_(3)](https://www.chedong.com/phpMan.php/man/system/3/markdown) function. It executes the shell command _cmd_ with
           Bourne Shell ("sh") and suspends the current threads execution until this command termi‐
           nates. The difference between [_system_(3)](https://www.chedong.com/phpMan.php/man/system/3/markdown) and [_pth_system_(3)](https://www.chedong.com/phpMan.php/man/pthsystem/3/markdown) is that [_pth_system_(3)](https://www.chedong.com/phpMan.php/man/pthsystem/3/markdown) suspends
           only the execution of the current thread and not the whole process. For more details
           about the arguments and return code semantics see [_system_(3)](https://www.chedong.com/phpMan.php/man/system/3/markdown).

       int **pth**___**sigmask**(int _how_, const sigset_t *_set_, sigset_t *_oset_)
           This is the **Pth** thread-related equivalent of POSIX [_sigprocmask_(2)](https://www.chedong.com/phpMan.php/man/sigprocmask/2/markdown) respectively
           [_pthread_sigmask_(3)](https://www.chedong.com/phpMan.php/man/pthreadsigmask/3/markdown). The arguments _how_, _set_ and _oset_ directly relate to [_sigprocmask_(2)](https://www.chedong.com/phpMan.php/man/sigprocmask/2/markdown),
           because **Pth** internally just uses [_sigprocmask_(2)](https://www.chedong.com/phpMan.php/man/sigprocmask/2/markdown) here. So alternatively you can also di‐
           rectly call [_sigprocmask_(2)](https://www.chedong.com/phpMan.php/man/sigprocmask/2/markdown), but for consistency reasons you should use this function
           [_pth_sigmask_(3)](https://www.chedong.com/phpMan.php/man/pthsigmask/3/markdown).

       int **pth**___**sigwait**(const sigset_t *_set_, int *_sig_);
           This is a variant of the POSIX.1c [_sigwait_(3)](https://www.chedong.com/phpMan.php/man/sigwait/3/markdown) function. It suspends the current threads
           execution until a signal in _set_ occurred and stores the signal number in _sig_. The impor‐
           tant point is that the signal is not delivered to a signal handler. Instead it's caught
           by the scheduler only in order to awake the _pth_sigwait()_ call. The trick and noticeable
           point here is that this way you get an asynchronous aware application that is written
           completely synchronously. When you think about the problem of _asynchronous_ _safe_ functions
           you should recognize that this is a great benefit.

       int **pth**___**connect**(int _s_, const struct sockaddr *_addr_, socklen_t _addrlen_);
           This is a variant of the 4.2BSD [_connect_(2)](https://www.chedong.com/phpMan.php/man/connect/2/markdown) function. It establishes a connection on a
           socket _s_ to target specified in _addr_ and _addrlen_.  The difference between [_connect_(2)](https://www.chedong.com/phpMan.php/man/connect/2/markdown) and
           [_pth_connect_(3)](https://www.chedong.com/phpMan.php/man/pthconnect/3/markdown) is that [_pth_connect_(3)](https://www.chedong.com/phpMan.php/man/pthconnect/3/markdown) suspends only the execution of the current thread
           and not the whole process.  For more details about the arguments and return code seman‐
           tics see [_connect_(2)](https://www.chedong.com/phpMan.php/man/connect/2/markdown).

       int **pth**___**accept**(int _s_, struct sockaddr *_addr_, socklen_t *_addrlen_);
           This is a variant of the 4.2BSD [_accept_(2)](https://www.chedong.com/phpMan.php/man/accept/2/markdown) function. It accepts a connection on a socket
           by extracting the first connection request on the queue of pending connections, creating
           a new socket with the same properties of _s_ and allocates a new file descriptor for the
           socket (which is returned).  The difference between [_accept_(2)](https://www.chedong.com/phpMan.php/man/accept/2/markdown) and [_pth_accept_(3)](https://www.chedong.com/phpMan.php/man/pthaccept/3/markdown) is that
           [_pth_accept_(3)](https://www.chedong.com/phpMan.php/man/pthaccept/3/markdown) suspends only the execution of the current thread and not the whole
           process.  For more details about the arguments and return code semantics see [_accept_(2)](https://www.chedong.com/phpMan.php/man/accept/2/markdown).

       int **pth**___**select**(int _nfd_, fd_set *_rfds_, fd_set *_wfds_, fd_set *_efds_, struct timeval *_timeout_);
           This is a variant of the 4.2BSD [_select_(2)](https://www.chedong.com/phpMan.php/man/select/2/markdown) function.  It examines the I/O descriptor sets
           whose addresses are passed in _rfds_, _wfds_, and _efds_ to see if some of their descriptors
           are ready for reading, are ready for writing, or have an exceptional condition pending,
           respectively.  For more details about the arguments and return code semantics see _se__‐
           [_lect_(2)](https://www.chedong.com/phpMan.php/man/lect/2/markdown).

       int **pth**___**pselect**(int _nfd_, fd_set *_rfds_, fd_set *_wfds_, fd_set *_efds_, const struct timespec
       *_timeout_, const sigset_t *_sigmask_);
           This is a variant of the POSIX [_pselect_(2)](https://www.chedong.com/phpMan.php/man/pselect/2/markdown) function, which in turn is a stronger variant
           of 4.2BSD [_select_(2)](https://www.chedong.com/phpMan.php/man/select/2/markdown). The difference is that the higher-resolution "struct timespec" is
           passed instead of the lower-resolution "struct timeval" and that a signal mask is speci‐
           fied which is temporarily set while waiting for input. For more details about the argu‐
           ments and return code semantics see [_pselect_(2)](https://www.chedong.com/phpMan.php/man/pselect/2/markdown) and [_select_(2)](https://www.chedong.com/phpMan.php/man/select/2/markdown).

       int **pth**___**poll**(struct pollfd *_fds_, unsigned int _nfd_, int _timeout_);
           This is a variant of the SysV [_poll_(2)](https://www.chedong.com/phpMan.php/man/poll/2/markdown) function. It examines the I/O descriptors which are
           passed in the array _fds_ to see if some of them are ready for reading, are ready for writ‐
           ing, or have an exceptional condition pending, respectively. For more details about the
           arguments and return code semantics see [_poll_(2)](https://www.chedong.com/phpMan.php/man/poll/2/markdown).

       ssize_t **pth**___**read**(int _fd_, void *_buf_, size_t _nbytes_);
           This is a variant of the POSIX [_read_(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown) function. It reads up to _nbytes_ bytes into _buf_
           from file descriptor _fd_.  The difference between [_read_(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown) and [_pth_read_(2)](https://www.chedong.com/phpMan.php/man/pthread/2/markdown) is that
           [_pth_read_(2)](https://www.chedong.com/phpMan.php/man/pthread/2/markdown) suspends execution of the current thread until the file descriptor is ready
           for reading. For more details about the arguments and return code semantics see [_read_(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown).

       ssize_t **pth**___**readv**(int _fd_, const struct iovec *_iovec_, int _iovcnt_);
           This is a variant of the POSIX [_readv_(2)](https://www.chedong.com/phpMan.php/man/readv/2/markdown) function. It reads data from file descriptor _fd_
           into the first _iovcnt_ rows of the _iov_ vector.  The difference between [_readv_(2)](https://www.chedong.com/phpMan.php/man/readv/2/markdown) and
           [_pth_readv_(2)](https://www.chedong.com/phpMan.php/man/pthreadv/2/markdown) is that [_pth_readv_(2)](https://www.chedong.com/phpMan.php/man/pthreadv/2/markdown) suspends execution of the current thread until the file
           descriptor is ready for reading. For more details about the arguments and return code se‐
           mantics see [_readv_(2)](https://www.chedong.com/phpMan.php/man/readv/2/markdown).

       ssize_t **pth**___**write**(int _fd_, const void *_buf_, size_t _nbytes_);
           This is a variant of the POSIX [_write_(2)](https://www.chedong.com/phpMan.php/man/write/2/markdown) function. It writes _nbytes_ bytes from _buf_ to file
           descriptor _fd_.  The difference between [_write_(2)](https://www.chedong.com/phpMan.php/man/write/2/markdown) and [_pth_write_(2)](https://www.chedong.com/phpMan.php/man/pthwrite/2/markdown) is that [_pth_write_(2)](https://www.chedong.com/phpMan.php/man/pthwrite/2/markdown)
           suspends execution of the current thread until the file descriptor is ready for writing.
           For more details about the arguments and return code semantics see [_write_(2)](https://www.chedong.com/phpMan.php/man/write/2/markdown).

       ssize_t **pth**___**writev**(int _fd_, const struct iovec *_iovec_, int _iovcnt_);
           This is a variant of the POSIX [_writev_(2)](https://www.chedong.com/phpMan.php/man/writev/2/markdown) function. It writes data to file descriptor _fd_
           from the first _iovcnt_ rows of the _iov_ vector.  The difference between [_writev_(2)](https://www.chedong.com/phpMan.php/man/writev/2/markdown) and
           [_pth_writev_(2)](https://www.chedong.com/phpMan.php/man/pthwritev/2/markdown) is that [_pth_writev_(2)](https://www.chedong.com/phpMan.php/man/pthwritev/2/markdown) suspends execution of the current thread until the
           file descriptor is ready for reading. For more details about the arguments and return
           code semantics see [_writev_(2)](https://www.chedong.com/phpMan.php/man/writev/2/markdown).

       ssize_t **pth**___**pread**(int _fd_, void *_buf_, size_t _nbytes_, off_t _offset_);
           This is a variant of the POSIX [_pread_(3)](https://www.chedong.com/phpMan.php/man/pread/3/markdown) function.  It performs the same action as a regu‐
           lar [_read_(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown), except that it reads from a given position in the file without changing the
           file pointer.  The first three arguments are the same as for [_pth_read_(3)](https://www.chedong.com/phpMan.php/man/pthread/3/markdown) with the addi‐
           tion of a fourth argument _offset_ for the desired position inside the file.

       ssize_t **pth**___**pwrite**(int _fd_, const void *_buf_, size_t _nbytes_, off_t _offset_);
           This is a variant of the POSIX [_pwrite_(3)](https://www.chedong.com/phpMan.php/man/pwrite/3/markdown) function.  It performs the same action as a reg‐
           ular [_write_(2)](https://www.chedong.com/phpMan.php/man/write/2/markdown), except that it writes to a given position in the file without changing the
           file pointer. The first three arguments are the same as for [_pth_write_(3)](https://www.chedong.com/phpMan.php/man/pthwrite/3/markdown) with the addi‐
           tion of a fourth argument _offset_ for the desired position inside the file.

       ssize_t **pth**___**recv**(int _fd_, void *_buf_, size_t _nbytes_, int _flags_);
           This is a variant of the SUSv2 [_recv_(2)](https://www.chedong.com/phpMan.php/man/recv/2/markdown) function and equal to ``pth_recvfrom(fd, buf,
           nbytes, flags, NULL, 0)''.

       ssize_t **pth**___**recvfrom**(int _fd_, void *_buf_, size_t _nbytes_, int _flags_, struct sockaddr *_from_,
       socklen_t *_fromlen_);
           This is a variant of the SUSv2 [_recvfrom_(2)](https://www.chedong.com/phpMan.php/man/recvfrom/2/markdown) function. It reads up to _nbytes_ bytes into _buf_
           from file descriptor _fd_ while using _flags_ and _from_/_fromlen_. The difference between
           [_recvfrom_(2)](https://www.chedong.com/phpMan.php/man/recvfrom/2/markdown) and [_pth_recvfrom_(2)](https://www.chedong.com/phpMan.php/man/pthrecvfrom/2/markdown) is that [_pth_recvfrom_(2)](https://www.chedong.com/phpMan.php/man/pthrecvfrom/2/markdown) suspends execution of the current
           thread until the file descriptor is ready for reading. For more details about the argu‐
           ments and return code semantics see [_recvfrom_(2)](https://www.chedong.com/phpMan.php/man/recvfrom/2/markdown).

       ssize_t **pth**___**send**(int _fd_, const void *_buf_, size_t _nbytes_, int _flags_);
           This is a variant of the SUSv2 [_send_(2)](https://www.chedong.com/phpMan.php/man/send/2/markdown) function and equal to ``pth_sendto(fd, buf,
           nbytes, flags, NULL, 0)''.

       ssize_t **pth**___**sendto**(int _fd_, const void *_buf_, size_t _nbytes_, int _flags_, const struct sockaddr
       *_to_, socklen_t _tolen_);
           This is a variant of the SUSv2 [_sendto_(2)](https://www.chedong.com/phpMan.php/man/sendto/2/markdown) function. It writes _nbytes_ bytes from _buf_ to
           file descriptor _fd_ while using _flags_ and _to_/_tolen_. The difference between [_sendto_(2)](https://www.chedong.com/phpMan.php/man/sendto/2/markdown) and
           [_pth_sendto_(2)](https://www.chedong.com/phpMan.php/man/pthsendto/2/markdown) is that [_pth_sendto_(2)](https://www.chedong.com/phpMan.php/man/pthsendto/2/markdown) suspends execution of the current thread until the
           file descriptor is ready for writing. For more details about the arguments and return
           code semantics see [_sendto_(2)](https://www.chedong.com/phpMan.php/man/sendto/2/markdown).

## EXAMPLE
       The following example is a useless server which does nothing more than listening on TCP port
       12345 and displaying the current time to the socket when a connection was established. For
       each incoming connection a thread is spawned. Additionally, to see more multithreading, a
       useless ticker thread runs simultaneously which outputs the current time to "stderr" every 5
       seconds. The example contains _no_ error checking and is _only_ intended to show you the look and
       feel of **Pth**.

        #include <stdio.h>
        #include <stdlib.h>
        #include <errno.h>
        #include <sys/types.h>
        #include <sys/socket.h>
        #include <netinet/in.h>
        #include <arpa/inet.h>
        #include <signal.h>
        #include <netdb.h>
        #include <unistd.h>
        #include "pth.h"

        #define PORT 12345

        /* the socket connection handler thread */
        static void *handler(void *_arg)
        {
            int fd = (int)_arg;
            time_t now;
            char *ct;

            now = time(NULL);
            ct = ctime(&now);
            pth_write(fd, ct, strlen(ct));
            close(fd);
            return NULL;
        }

        /* the stderr time ticker thread */
        static void *ticker(void *_arg)
        {
            time_t now;
            char *ct;
            float load;

            for (;;) {
                [pth_sleep(5)](https://www.chedong.com/phpMan.php/man/pthsleep/5/markdown);
                now = time(NULL);
                ct = ctime(&now);
                ct[strlen(ct)-1] = '\0';
                pth_ctrl(PTH_CTRL_GETAVLOAD, &load);
                printf("ticker: time: %s, average load: %.2f\n", ct, load);
            }
        }

        /* the main thread/procedure */
        int main(int argc, char *argv[])
        {
            pth_attr_t attr;
            struct sockaddr_in sar;
            struct protoent *pe;
            struct sockaddr_in peer_addr;
            int peer_len;
            int sa, sw;
            int port;

            pth_init();
            signal(SIGPIPE, SIG_IGN);

            attr = pth_attr_new();
            pth_attr_set(attr, PTH_ATTR_NAME, "ticker");
            pth_attr_set(attr, PTH_ATTR_STACK_SIZE, 64*1024);
            pth_attr_set(attr, PTH_ATTR_JOINABLE, FALSE);
            pth_spawn(attr, ticker, NULL);

            pe = getprotobyname("tcp");
            sa = socket(AF_INET, SOCK_STREAM, pe->p_proto);
            sar.sin_family = AF_INET;
            sar.sin_addr.s_addr = INADDR_ANY;
            sar.sin_port = htons(PORT);
            bind(sa, (struct sockaddr *)&sar, sizeof(struct sockaddr_in));
            listen(sa, 10);

            pth_attr_set(attr, PTH_ATTR_NAME, "handler");
            for (;;) {
                peer_len = sizeof(peer_addr);
                sw = pth_accept(sa, (struct sockaddr *)&peer_addr, &peer_len);
                pth_spawn(attr, handler, (void *)sw);
            }
        }

## BUILD ENVIRONMENTS
       In this section we will discuss the canonical ways to establish the build environment for a
       **Pth** based program. The possibilities supported by **Pth** range from very simple environments to
       rather complex ones.

### Manual Build Environment (Novice)

       As a first example, assume we have the above test program staying in the source file "foo.c".
       Then we can create a very simple build environment by just adding the following "Makefile":

        $ vi Makefile
        ⎪ CC      = cc
        ⎪ CFLAGS  = `pth-config --cflags`
        ⎪ LDFLAGS = `pth-config --ldflags`
        ⎪ LIBS    = `pth-config --libs`
        ⎪
        ⎪ all: foo
        ⎪ foo: foo.o
        ⎪     $(CC) $(LDFLAGS) -o foo foo.o $(LIBS)
        ⎪ foo.o: foo.c
        ⎪     $(CC) $(CFLAGS) -c foo.c
        ⎪ clean:
        ⎪     rm -f foo foo.o

       This imports the necessary compiler and linker flags on-the-fly from the **Pth** installation via
       its "pth-config" program. This approach is straight-forward and works fine for small
       projects.

### Autoconf Build Environment (Advanced)

       The previous approach is simple but inflexible. First, to speed up building, it would be nice
       to not expand the compiler and linker flags every time the compiler is started. Second, it
       would be useful to also be able to build against uninstalled **Pth**, that is, against a **Pth**
       source tree which was just configured and built, but not installed. Third, it would be also
       useful to allow checking of the **Pth** version to make sure it is at least a minimum required
       version.  And finally, it would be also great to make sure **Pth** works correctly by first per‐
       forming some sanity compile and run-time checks. All this can be done if we use GNU **autoconf**
       and the "AC_CHECK_PTH" macro provided by **Pth**. For this, we establish the following three
       files:

       First we again need the "Makefile", but this time it contains **autoconf** placeholders and addi‐
       tional cleanup targets. And we create it under the name "Makefile.in", because it is now an
       input file for **autoconf**:

        $ vi Makefile.in
        ⎪ CC      = @CC@
        ⎪ CFLAGS  = @CFLAGS@
        ⎪ LDFLAGS = @LDFLAGS@
        ⎪ LIBS    = @LIBS@
        ⎪
        ⎪ all: foo
        ⎪ foo: foo.o
        ⎪     $(CC) $(LDFLAGS) -o foo foo.o $(LIBS)
        ⎪ foo.o: foo.c
        ⎪     $(CC) $(CFLAGS) -c foo.c
        ⎪ clean:
        ⎪     rm -f foo foo.o
        ⎪ distclean:
        ⎪     rm -f foo foo.o
        ⎪     rm -f config.log config.status config.cache
        ⎪     rm -f Makefile

       Because **autoconf** generates additional files, we added a canonical "distclean" target which
       cleans this up. Secondly, we wrote "configure.ac", a (minimal) **autoconf** script specification:

        $ vi configure.ac
        ⎪ AC_INIT(Makefile.in)
        ⎪ AC_CHECK_PTH(1.3.0)
        ⎪ AC_OUTPUT(Makefile)

       Then we let **autoconf**'s "aclocal" program generate for us an "aclocal.m4" file containing
       **Pth**'s "AC_CHECK_PTH" macro. Then we generate the final "configure" script out of this "aclo‐
       cal.m4" file and the "configure.ac" file:

        $ aclocal --acdir=`pth-config --acdir`
        $ autoconf

       After these steps, the working directory should look similar to this:

        $ ls -l
        -rw-r--r--  1 rse  users    176 Nov  3 11:11 Makefile.in
        -rw-r--r--  1 rse  users  15314 Nov  3 11:16 aclocal.m4
        -rwxr-xr-x  1 rse  users  52045 Nov  3 11:16 configure
        -rw-r--r--  1 rse  users     63 Nov  3 11:11 configure.ac
        -rw-r--r--  1 rse  users   4227 Nov  3 11:11 foo.c

       If we now run "configure" we get a correct "Makefile" which immediately can be used to build
       "foo" (assuming that **Pth** is already installed somewhere, so that "pth-config" is in $PATH):

        $ ./configure
        creating cache ./config.cache
        checking for gcc... gcc
        checking whether the C compiler (gcc   ) works... yes
        checking whether the C compiler (gcc   ) is a cross-compiler... no
        checking whether we are using GNU C... yes
        checking whether gcc accepts -g... yes
        checking how to run the C preprocessor... gcc -E
        checking for GNU Pth... version 1.3.0, installed under /usr/local
        updating cache ./config.cache
        creating ./config.status
        creating Makefile
        rse@en1:/e/gnu/pth/ac
        $ make
        gcc -g -O2 -I/usr/local/include -c foo.c
        gcc -L/usr/local/lib -o foo foo.o -lpth

       If **Pth** is installed in non-standard locations or "pth-config" is not in $PATH, one just has
       to drop the "configure" script a note about the location by running "configure" with the op‐
       tion "--with-pth="_dir_ (where _dir_ is the argument which was used with the "--prefix" option
       when **Pth** was installed).

### Autoconf Build Environment with Local Copy of Pth (Expert)

       Finally let us assume the "foo" program stays under either a _GPL_ or _LGPL_ distribution license
       and we want to make it a stand-alone package for easier distribution and installation.  That
       is, we don't want to oblige the end-user to install **Pth** just to allow our "foo" package to
       compile. For this, it is a convenient practice to include the required libraries (here **Pth**)
       into the source tree of the package (here "foo").  **Pth** ships with all necessary support to
       allow us to easily achieve this approach. Say, we want **Pth** in a subdirectory named "pth/" and
       this directory should be seamlessly integrated into the configuration and build process of
       "foo".

       First we again start with the "Makefile.in", but this time it is a more advanced version
       which supports subdirectory movement:

        $ vi Makefile.in
        ⎪ CC      = @CC@
        ⎪ CFLAGS  = @CFLAGS@
        ⎪ LDFLAGS = @LDFLAGS@
        ⎪ LIBS    = @LIBS@
        ⎪
        ⎪ SUBDIRS = pth
        ⎪
        ⎪ all: subdirs_all foo
        ⎪
        ⎪ subdirs_all:
        ⎪     @$(MAKE) $(MFLAGS) subdirs TARGET=all
        ⎪ subdirs_clean:
        ⎪     @$(MAKE) $(MFLAGS) subdirs TARGET=clean
        ⎪ subdirs_distclean:
        ⎪     @$(MAKE) $(MFLAGS) subdirs TARGET=distclean
        ⎪ subdirs:
        ⎪     @for subdir in $(SUBDIRS); do \
        ⎪         echo "===> $$subdir ($(TARGET))"; \
        ⎪         (cd $$subdir; $(MAKE) $(MFLAGS) $(TARGET) ⎪⎪ exit 1) ⎪⎪ exit 1; \
        ⎪         echo "<=== $$subdir"; \
        ⎪     done
        ⎪
        ⎪ foo: foo.o
        ⎪     $(CC) $(LDFLAGS) -o foo foo.o $(LIBS)
        ⎪ foo.o: foo.c
        ⎪     $(CC) $(CFLAGS) -c foo.c
        ⎪
        ⎪ clean: subdirs_clean
        ⎪     rm -f foo foo.o
        ⎪ distclean: subdirs_distclean
        ⎪     rm -f foo foo.o
        ⎪     rm -f config.log config.status config.cache
        ⎪     rm -f Makefile

       Then we create a slightly different **autoconf** script "configure.ac":

        $ vi configure.ac
        ⎪ AC_INIT(Makefile.in)
        ⎪ AC_CONFIG_AUX_DIR(pth)
        ⎪ AC_CHECK_PTH(1.3.0, subdir:pth --disable-tests)
        ⎪ AC_CONFIG_SUBDIRS(pth)
        ⎪ AC_OUTPUT(Makefile)

       Here we provided a default value for "foo"'s "--with-pth" option as the second argument to
       "AC_CHECK_PTH" which indicates that **Pth** can be found in the subdirectory named "pth/". Addi‐
       tionally we specified that the "--disable-tests" option of **Pth** should be passed to the "pth/"
       subdirectory, because we need only to build the **Pth** library itself. And we added a "AC_CON‐
       FIG_SUBDIR" call which indicates to **autoconf** that it should configure the "pth/" subdirec‐
       tory, too. The "AC_CONFIG_AUX_DIR" directive was added just to make **autoconf** happy, because
       it wants to find a "install.sh" or "shtool" script if "AC_CONFIG_SUBDIRS" is used.

       Now we let **autoconf**'s "aclocal" program again generate for us an "aclocal.m4" file with the
       contents of **Pth**'s "AC_CHECK_PTH" macro.  Finally we generate the "configure" script out of
       this "aclocal.m4" file and the "configure.ac" file.

        $ aclocal --acdir=`pth-config --acdir`
        $ autoconf

       Now we have to create the "pth/" subdirectory itself. For this, we extract the **Pth** distribu‐
       tion to the "foo" source tree and just rename it to "pth/":

        $ gunzip <pth-X.Y.Z.tar.gz ⎪ tar xvf -
        $ mv pth-X.Y.Z pth

       Optionally to reduce the size of the "pth/" subdirectory, we can strip down the **Pth** sources
       to a minimum with the _striptease_ feature:

        $ cd pth
        $ ./configure
        $ make striptease
        $ cd ..

       After this the source tree of "foo" should look similar to this:

        $ ls -l
        -rw-r--r--  1 rse  users    709 Nov  3 11:51 Makefile.in
        -rw-r--r--  1 rse  users  16431 Nov  3 12:20 aclocal.m4
        -rwxr-xr-x  1 rse  users  57403 Nov  3 12:21 configure
        -rw-r--r--  1 rse  users    129 Nov  3 12:21 configure.ac
        -rw-r--r--  1 rse  users   4227 Nov  3 11:11 foo.c
        drwxr-xr-x  2 rse  users   3584 Nov  3 12:36 pth
        $ ls -l pth/
        -rw-rw-r--  1 rse  users   26344 Nov  1 20:12 COPYING
        -rw-rw-r--  1 rse  users    2042 Nov  3 12:36 Makefile.in
        -rw-rw-r--  1 rse  users    3967 Nov  1 19:48 README
        -rw-rw-r--  1 rse  users     340 Nov  3 12:36 README.1st
        -rw-rw-r--  1 rse  users   28719 Oct 31 17:06 config.guess
        -rw-rw-r--  1 rse  users   24274 Aug 18 13:31 config.sub
        -rwxrwxr-x  1 rse  users  155141 Nov  3 12:36 configure
        -rw-rw-r--  1 rse  users  162021 Nov  3 12:36 pth.c
        -rw-rw-r--  1 rse  users   18687 Nov  2 15:19 pth.h.in
        -rw-rw-r--  1 rse  users    5251 Oct 31 12:46 pth_acdef.h.in
        -rw-rw-r--  1 rse  users    2120 Nov  1 11:27 pth_acmac.h.in
        -rw-rw-r--  1 rse  users    2323 Nov  1 11:27 pth_p.h.in
        -rw-rw-r--  1 rse  users     946 Nov  1 11:27 pth_vers.c
        -rw-rw-r--  1 rse  users   26848 Nov  1 11:27 pthread.c
        -rw-rw-r--  1 rse  users   18772 Nov  1 11:27 pthread.h.in
        -rwxrwxr-x  1 rse  users   26188 Nov  3 12:36 shtool

       Now when we configure and build the "foo" package it looks similar to this:

        $ ./configure
        creating cache ./config.cache
        checking for gcc... gcc
        checking whether the C compiler (gcc   ) works... yes
        checking whether the C compiler (gcc   ) is a cross-compiler... no
        checking whether we are using GNU C... yes
        checking whether gcc accepts -g... yes
        checking how to run the C preprocessor... gcc -E
        checking for GNU Pth... version 1.3.0, local under pth
        updating cache ./config.cache
        creating ./config.status
        creating Makefile
        configuring in pth
        running /bin/sh ./configure  --enable-subdir --enable-batch
        --disable-tests --cache-file=.././config.cache --srcdir=.
        loading cache .././config.cache
        checking for gcc... (cached) gcc
        checking whether the C compiler (gcc   ) works... yes
        checking whether the C compiler (gcc   ) is a cross-compiler... no
        [...]
        $ make
        ===> pth (all)
        ./shtool scpp -o pth_p.h -t pth_p.h.in -Dcpp -Cintern -M '==#==' pth.c
        pth_vers.c
        gcc -c -I. -O2 -pipe pth.c
        gcc -c -I. -O2 -pipe pth_vers.c
        ar rc libpth.a pth.o pth_vers.o
        ranlib libpth.a
        <=== pth
        gcc -g -O2 -Ipth -c foo.c
        gcc -Lpth -o foo foo.o -lpth

       As you can see, **autoconf** now automatically configures the local (stripped down) copy of **Pth**
       in the subdirectory "pth/" and the "Makefile" automatically builds the subdirectory, too.

## SYSTEM CALL WRAPPER FACILITY
       **Pth** per default uses an explicit API, including the system calls. For instance you've to ex‐
       plicitly use [_pth_read_(3)](https://www.chedong.com/phpMan.php/man/pthread/3/markdown) when you need a thread-aware [_read_(3)](https://www.chedong.com/phpMan.php/man/read/3/markdown) and cannot expect that by just
       calling [_read_(3)](https://www.chedong.com/phpMan.php/man/read/3/markdown) only the current thread is blocked. Instead with the standard [_read_(3)](https://www.chedong.com/phpMan.php/man/read/3/markdown) call
       the whole process will be blocked. But because for some applications (mainly those consisting
       of lots of third-party stuff) this can be inconvenient.  Here it's required that a call to
       [_read_(3)](https://www.chedong.com/phpMan.php/man/read/3/markdown) `magically' means [_pth_read_(3)](https://www.chedong.com/phpMan.php/man/pthread/3/markdown). The problem here is that such magic **Pth** cannot provide
       per default because it's not really portable.  Nevertheless **Pth** provides a two step approach
       to solve this problem:

### Soft System Call Mapping

       This variant is available on all platforms and can _always_ be enabled by building **Pth** with
       "--enable-syscall-soft". This then triggers some "#define"'s in the "pth.h" header which map
       for instance [_read_(3)](https://www.chedong.com/phpMan.php/man/read/3/markdown) to [_pth_read_(3)](https://www.chedong.com/phpMan.php/man/pthread/3/markdown), etc. Currently the following functions are mapped:
       [_fork_(2)](https://www.chedong.com/phpMan.php/man/fork/2/markdown), [_nanosleep_(3)](https://www.chedong.com/phpMan.php/man/nanosleep/3/markdown), [_usleep_(3)](https://www.chedong.com/phpMan.php/man/usleep/3/markdown), [_sleep_(3)](https://www.chedong.com/phpMan.php/man/sleep/3/markdown), [_sigwait_(3)](https://www.chedong.com/phpMan.php/man/sigwait/3/markdown), [_waitpid_(2)](https://www.chedong.com/phpMan.php/man/waitpid/2/markdown), [_system_(3)](https://www.chedong.com/phpMan.php/man/system/3/markdown), [_select_(2)](https://www.chedong.com/phpMan.php/man/select/2/markdown),
       [_poll_(2)](https://www.chedong.com/phpMan.php/man/poll/2/markdown), [_connect_(2)](https://www.chedong.com/phpMan.php/man/connect/2/markdown), [_accept_(2)](https://www.chedong.com/phpMan.php/man/accept/2/markdown), [_read_(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown), [_write_(2)](https://www.chedong.com/phpMan.php/man/write/2/markdown), [_recv_(2)](https://www.chedong.com/phpMan.php/man/recv/2/markdown), [_send_(2)](https://www.chedong.com/phpMan.php/man/send/2/markdown), [_recvfrom_(2)](https://www.chedong.com/phpMan.php/man/recvfrom/2/markdown), [_sendto_(2)](https://www.chedong.com/phpMan.php/man/sendto/2/markdown).

       The drawback of this approach is just that really all source files of the application where
       these function calls occur have to include "pth.h", of course. And this also means that ex‐
       isting libraries, including the vendor's **stdio**, usually will still block the whole process if
       one of its I/O functions block.

### Hard System Call Mapping

       This variant is available only on those platforms where the [_syscall_(2)](https://www.chedong.com/phpMan.php/man/syscall/2/markdown) function exists and
       there it can be enabled by building **Pth** with "--enable-syscall-hard". This then builds wrap‐
       per functions (for instances [_read_(3)](https://www.chedong.com/phpMan.php/man/read/3/markdown)) into the **Pth** library which internally call the real **Pth**
       replacement functions ([_pth_read_(3)](https://www.chedong.com/phpMan.php/man/pthread/3/markdown)). Currently the following functions are mapped: [_fork_(2)](https://www.chedong.com/phpMan.php/man/fork/2/markdown),
       [_nanosleep_(3)](https://www.chedong.com/phpMan.php/man/nanosleep/3/markdown), [_usleep_(3)](https://www.chedong.com/phpMan.php/man/usleep/3/markdown), [_sleep_(3)](https://www.chedong.com/phpMan.php/man/sleep/3/markdown), [_waitpid_(2)](https://www.chedong.com/phpMan.php/man/waitpid/2/markdown), [_system_(3)](https://www.chedong.com/phpMan.php/man/system/3/markdown), [_select_(2)](https://www.chedong.com/phpMan.php/man/select/2/markdown), [_poll_(2)](https://www.chedong.com/phpMan.php/man/poll/2/markdown), [_connect_(2)](https://www.chedong.com/phpMan.php/man/connect/2/markdown), _ac__‐
       [_cept_(2)](https://www.chedong.com/phpMan.php/man/cept/2/markdown), [_read_(2)](https://www.chedong.com/phpMan.php/man/read/2/markdown), [_write_(2)](https://www.chedong.com/phpMan.php/man/write/2/markdown).

       The drawback of this approach is that it depends on [_syscall_(2)](https://www.chedong.com/phpMan.php/man/syscall/2/markdown) interface and prototype con‐
       flicts can occur while building the wrapper functions due to different function signatures in
       the vendor C header files.  But the advantage of this mapping variant is that the source
       files of the application where these function calls occur have not to include "pth.h" and
       that existing libraries, including the vendor's **stdio**, magically become thread-aware (and
       then block only the current thread).

## IMPLEMENTATION NOTES
       **Pth** is very portable because it has only one part which perhaps has to be ported to new plat‐
       forms (the machine context initialization). But it is written in a way which works on mostly
       all Unix platforms which support [_makecontext_(2)](https://www.chedong.com/phpMan.php/man/makecontext/2/markdown) or at least [_sigstack_(2)](https://www.chedong.com/phpMan.php/man/sigstack/2/markdown) or [_sigaltstack_(2)](https://www.chedong.com/phpMan.php/man/sigaltstack/2/markdown)
       [see "pth_mctx.c" for details]. Any other **Pth** code is POSIX and ANSI C based only.

       The context switching is done via either SUSv2 [_makecontext_(2)](https://www.chedong.com/phpMan.php/man/makecontext/2/markdown) or POSIX make[sig][_setjmp_(3)](https://www.chedong.com/phpMan.php/man/setjmp/3/markdown) and
       [sig][_longjmp_(3)](https://www.chedong.com/phpMan.php/man/longjmp/3/markdown). Here all CPU registers, the program counter and the stack pointer are
       switched. Additionally the **Pth** dispatcher switches also the global Unix "errno" variable [see
       "pth_mctx.c" for details] and the signal mask (either implicitly via [_sigsetjmp_(3)](https://www.chedong.com/phpMan.php/man/sigsetjmp/3/markdown) or in an
       emulated way via explicit [_setprocmask_(2)](https://www.chedong.com/phpMan.php/man/setprocmask/2/markdown) calls).

       The **Pth** event manager is mainly [_select_(2)](https://www.chedong.com/phpMan.php/man/select/2/markdown) and [_gettimeofday_(2)](https://www.chedong.com/phpMan.php/man/gettimeofday/2/markdown) based, i.e., the current time
       is fetched via [_gettimeofday_(2)](https://www.chedong.com/phpMan.php/man/gettimeofday/2/markdown) once per context switch for time calculations and all I/O
       events are implemented via a single central [_select_(2)](https://www.chedong.com/phpMan.php/man/select/2/markdown) call [see "pth_sched.c" for details].

       The thread control block management is done via virtual priority queues without any addi‐
       tional data structure overhead. For this, the queue linkage attributes are part of the thread
       control blocks and the queues are actually implemented as rings with a selected element as
       the entry point [see "pth_tcb.h" and "pth_pqueue.c" for details].

       Most time critical code sections (especially the dispatcher and event manager) are speeded up
       by inline functions (implemented as ANSI C pre-processor macros). Additionally any debugging
       code is _completely_ removed from the source when not built with "-DPTH_DEBUG" (see Autoconf
       "--enable-debug" option), i.e., not only stub functions remain [see "pth_debug.c" for de‐
       tails].

## RESTRICTIONS
### Pth (intentionally)
       which uses a static internal buffer) or synchronous system functions (like [_gethostbyname_(3)](https://www.chedong.com/phpMan.php/man/gethostbyname/3/markdown)
       which doesn't provide an asynchronous mode where it doesn't block). When you want to use
       those functions in your server application together with threads, you've to either link the
       application against special third-party libraries (or for thread-safe/reentrant functions
       possibly against an existing "libc_r" of the platform vendor). For an asynchronous DNS re‐
       solver library use the GNU **adns** package from Ian Jackson ( see <http://www.gnu.org/soft>‐
       ware/adns/adns.html ).

## HISTORY
       The **Pth** library was designed and implemented between February and July 1999 by _Ralf_ _S._ _En__‐
       _gelschall_ after evaluating numerous (mostly preemptive) thread libraries and after intensive
       discussions with _Peter_ _Simons_, _Martin_ _Kraemer_, _Lars_ _Eilebrecht_ and _Ralph_ _Babel_ related to an
       experimental (matrix based) non-preemptive C++ scheduler class written by _Peter_ _Simons_.

       **Pth** was then implemented in order to combine the _non-preemptive_ approach of multithreading
       (which provides better portability and performance) with an API similar to the popular one
       found in **Pthread** libraries (which provides easy programming).

       So the essential idea of the non-preemptive approach was taken over from _Peter_ _Simons_ sched‐
       uler. The priority based scheduling algorithm was suggested by _Martin_ _Kraemer_. Some code in‐
       spiration also came from an experimental threading library (**rsthreads**) written by _Robert_ _S._
       _Thau_ for an ancient internal test version of the Apache webserver.  The concept and API of
       message ports was borrowed from AmigaOS' **Exec** subsystem. The concept and idea for the flexi‐
       ble event mechanism came from _Paul_ _Vixie_'s **eventlib** (which can be found as a part of **BIND**
       v8).

## BUG REPORTS AND SUPPORT
       If you think you have found a bug in **Pth**, you should send a report as complete as possible to
       <_bug-pth@gnu.org_>. If you can, please try to fix the problem and include a patch, made with
       '"diff -u3"', in your report. Always, at least, include a reasonable amount of description in
       your report to allow the author to deterministically reproduce the bug.

       For further support you additionally can subscribe to the <_pth-users@gnu.org_> mailing list by
       sending an Email to <_pth-users-request@gnu.org_> with `"subscribe pth-users"' (or `"subscribe
       pth-users" _address_' if you want to subscribe from a particular Email _address_) in the body.
       Then you can discuss your issues with other **Pth** users by sending messages to
       <_pth-users@gnu.org_>. Currently (as of August 2000) you can reach about 110 Pth users on this
       mailing list. Old postings you can find at _<http://www.mail-archive.com/><pth-users@gnu.org>/_.

## SEE ALSO
### Related Web Locations

       `comp.programming.threads Newsgroup Archive', <http://www.deja.com/topics_if.xp>?
       search=topic&group=comp.programming.threads

       `comp.programming.threads Frequently Asked Questions (F.A.Q.)', <http://www.lambdacs.com/news>‐
       group/FAQ.html

       `_Multithreading_ _-_ _Definitions_ _and_ _Guidelines_', Numeric Quest Inc 1998; <http://www.nu>‐
       meric-quest.com/lang/multi-frame.html

       `_The_ _Single_ _UNIX_ _Specification,_ _Version_ _2_ _-_ _Threads_', The Open Group 1997; <http://www.open>‐
       group.org/onlinepubs /007908799/xsh/threads.html

       SMI Thread Resources, Sun Microsystems Inc; <http://www.sun.com/workshop/threads/>

       Bibliography on threads and multithreading, Torsten Amundsen; <http://liinwww.ira.uka.de/bib>‐
       liography/Os/threads.html

### Related Books

       B. Nichols, D. Buttlar, J.P. Farrel: `_Pthreads_ _Programming_ _-_ _A_ _POSIX_ _Standard_ _for_ _Better_ _Mul__‐
       _tiprocessing_', O'Reilly 1996; ISBN 1-56592-115-1

       B. Lewis, D. J. Berg: `_Multithreaded_ _Programming_ _with_ _Pthreads_', Sun Microsystems Press,
       Prentice Hall 1998; ISBN 0-13-680729-1

       B. Lewis, D. J. Berg: `_Threads_ _Primer_ _-_ _A_ _Guide_ _To_ _Multithreaded_ _Programming_', Prentice Hall
       1996; ISBN 0-13-443698-9

       S. J. Norton, M. D. Dipasquale: `_Thread_ _Time_ _-_ _The_ _Multithreaded_ _Programming_ _Guide_', Prentice
       Hall 1997; ISBN 0-13-190067-6

       D. R. Butenhof: `_Programming_ _with_ _POSIX_ _Threads_', Addison Wesley 1997; ISBN 0-201-63392-2

### Related Manpages

       [_pth-config_(1)](https://www.chedong.com/phpMan.php/man/pth-config/1/markdown), [_pthread_(3)](https://www.chedong.com/phpMan.php/man/pthread/3/markdown).

       [_getcontext_(2)](https://www.chedong.com/phpMan.php/man/getcontext/2/markdown), [_setcontext_(2)](https://www.chedong.com/phpMan.php/man/setcontext/2/markdown), [_makecontext_(2)](https://www.chedong.com/phpMan.php/man/makecontext/2/markdown), [_swapcontext_(2)](https://www.chedong.com/phpMan.php/man/swapcontext/2/markdown), [_sigstack_(2)](https://www.chedong.com/phpMan.php/man/sigstack/2/markdown), [_sigaltstack_(2)](https://www.chedong.com/phpMan.php/man/sigaltstack/2/markdown),
       [_sigaction_(2)](https://www.chedong.com/phpMan.php/man/sigaction/2/markdown), [_sigemptyset_(2)](https://www.chedong.com/phpMan.php/man/sigemptyset/2/markdown), [_sigaddset_(2)](https://www.chedong.com/phpMan.php/man/sigaddset/2/markdown), [_sigprocmask_(2)](https://www.chedong.com/phpMan.php/man/sigprocmask/2/markdown), [_sigsuspend_(2)](https://www.chedong.com/phpMan.php/man/sigsuspend/2/markdown), [_sigsetjmp_(3)](https://www.chedong.com/phpMan.php/man/sigsetjmp/3/markdown), _sig__‐
       [_longjmp_(3)](https://www.chedong.com/phpMan.php/man/longjmp/3/markdown), [_setjmp_(3)](https://www.chedong.com/phpMan.php/man/setjmp/3/markdown), [_longjmp_(3)](https://www.chedong.com/phpMan.php/man/longjmp/3/markdown), [_select_(2)](https://www.chedong.com/phpMan.php/man/select/2/markdown), [_gettimeofday_(2)](https://www.chedong.com/phpMan.php/man/gettimeofday/2/markdown).

## AUTHOR
        Ralf S. Engelschall
        <rse@engelschall.com>
        www.engelschall.com



08-Jun-2006                                 GNU Pth 2.0.7                                     [pth(3)](https://www.chedong.com/phpMan.php/man/pth/3/markdown)
