{
    "mode": "man",
    "parameter": "pth",
    "section": "3",
    "url": "https://www.chedong.com/phpMan.php/man/pth/3/json",
    "generated": "2026-07-07T02:38:49Z",
    "synopsis": "",
    "sections": {
        "NAME": {
            "content": "pth - GNU Portable Threads\n",
            "subsections": []
        },
        "VERSION": {
            "content": "GNU Pth 2.0.7 (08-Jun-2006)\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "",
            "subsections": [
                {
                    "name": "Global Library Management",
                    "content": "pthinit, pthkill, pthctrl, pthversion.\n"
                },
                {
                    "name": "Thread Attribute Handling",
                    "content": "pthattrof, pthattrnew, pthattrinit, pthattrset, pthattrget, pthattrdestroy.\n"
                },
                {
                    "name": "Thread Control",
                    "content": "pthspawn, pthonce, pthself, pthsuspend, pthresume, pthyield, pthnap, pthwait,\npthcancel, pthabort, pthraise, pthjoin, pthexit.\n"
                },
                {
                    "name": "Utilities",
                    "content": "pthfdmode, pthtime, pthtimeout, pthsfiodisc.\n"
                },
                {
                    "name": "Cancellation Management",
                    "content": "pthcancelpoint, pthcancelstate.\n"
                },
                {
                    "name": "Event Handling",
                    "content": "pthevent, ptheventtypeof, ptheventextract, ptheventconcat, ptheventisolate,\nptheventwalk, ptheventstatus, ptheventfree.\n"
                },
                {
                    "name": "Key-Based Storage",
                    "content": "pthkeycreate, pthkeydelete, pthkeysetdata, pthkeygetdata.\n"
                },
                {
                    "name": "Message Port Communication",
                    "content": "pthmsgportcreate, pthmsgportdestroy, pthmsgportfind, pthmsgportpending, pthmsg‐\nportput, pthmsgportget, pthmsgportreply.\n"
                },
                {
                    "name": "Thread Cleanups",
                    "content": "pthcleanuppush, pthcleanuppop.\n"
                },
                {
                    "name": "Process Forking",
                    "content": "pthatforkpush, pthatforkpop, pthfork.\n"
                },
                {
                    "name": "Synchronization",
                    "content": "pthmutexinit, pthmutexacquire, pthmutexrelease, pthrwlockinit, pthrwlockac‐\nquire, pthrwlockrelease, pthcondinit, pthcondawait, pthcondnotify, pthbar‐\nrierinit, pthbarrierreach.\n"
                },
                {
                    "name": "User-Space Context",
                    "content": "pthuctxcreate, pthuctxmake, pthuctxswitch, pthuctxdestroy.\n"
                },
                {
                    "name": "Generalized POSIX Replacement API",
                    "content": "pthsigwaitev, pthacceptev, pthconnectev, pthselectev, pthpollev, pthreadev,\npthreadvev, pthwriteev, pthwritevev, pthrecvev, pthrecvfromev, pthsendev,\npthsendtoev.\n"
                },
                {
                    "name": "Standard POSIX Replacement API",
                    "content": "pthnanosleep, pthusleep, pthsleep, pthwaitpid, pthsystem, pthsigmask, pthsigwait,\npthaccept, pthconnect, pthselect, pthpselect, pthpoll, pthread, pthreadv,\npthwrite, pthwritev, pthpread, pthpwrite, pthrecv, pthrecvfrom, pthsend,\npthsendto.\n"
                }
            ]
        },
        "DESCRIPTION": {
            "content": "⎪   \\⎪ ⎪⎪ ⎪\n⎪ ⎪) ⎪ ⎪ ' \\         ``Only those who attempt\n⎪  /⎪ ⎪⎪ ⎪ ⎪ ⎪          the absurd can achieve\n⎪⎪    \\⎪⎪ ⎪⎪          the impossible.''\n\nPth is a very portable POSIX/ANSI-C based library for Unix platforms which provides non-pre‐\nemptive priority-based scheduling for multiple threads of execution (aka `multithreading')\ninside event-driven applications. All threads run in the same address space of the applica‐\ntion process, but each thread has its own individual program counter, run-time stack, signal\nmask and \"errno\" variable.\n\nThe thread scheduling itself is done in a cooperative way, i.e., the threads are managed and\ndispatched by a priority- and event-driven non-preemptive scheduler. The intention is that\nthis way both better portability and run-time performance is achieved than with preemptive\nscheduling. The event facility allows threads to wait until various types of internal and ex‐\nternal events occur, including pending I/O on file descriptors, asynchronous signals, elapsed\ntimers, pending I/O on message ports, thread and process termination, and even results of\ncustomized callback functions.\n\nPth also provides an optional emulation API for POSIX.1c threads (`Pthreads') which can be\nused for backward compatibility to existing multithreaded applications. See Pth's pthread(3)\nmanual page for details.\n",
            "subsections": [
                {
                    "name": "Threading Background",
                    "content": "When programming event-driven applications, usually servers, lots of regular jobs and one-\nshot requests have to be processed in parallel.  To efficiently simulate this parallel pro‐\ncessing on uniprocessor machines, we use `multitasking' -- that is, we have the application\nask the operating system to spawn multiple instances of itself. On Unix, typically the kernel\nimplements multitasking in a preemptive and priority-based way through heavy-weight processes\nspawned with fork(2).  These processes usually do not share a common address space. Instead\nthey are clearly separated from each other, and are created by direct cloning a process ad‐\ndress space (although modern kernels use memory segment mapping and copy-on-write semantics\nto avoid unnecessary copying of physical memory).\n\nThe drawbacks are obvious: Sharing data between the processes is complicated, and can usually\nonly be done efficiently through shared memory (but which itself is not very portable). Syn‐\nchronization is complicated because of the preemptive nature of the Unix scheduler (one has\nto use atomic locks, etc). The machine's resources can be exhausted very quickly when the\nserver application has to serve too many long-running requests (heavy-weight processes cost\nmemory). And when each request spawns a sub-process to handle it, the server performance and\nresponsiveness is horrible (heavy-weight processes cost time to spawn). Finally, the server\napplication doesn't scale very well with the load because of these resource problems. In\npractice, lots of tricks are usually used to overcome these problems - ranging from pre-\nforked sub-process pools to semi-serialized processing, etc.\n\nOne of the most elegant ways to solve these resource- and data-sharing problems is to have\nmultiple light-weight threads of execution inside a single (heavy-weight) process, i.e., to\nuse multithreading.  Those threads usually improve responsiveness and performance of the ap‐\nplication, often improve and simplify the internal program structure, and most important, re‐\nquire less system resources than heavy-weight processes. Threads are neither the optimal run-\ntime facility for all types of applications, nor can all applications benefit from them. But\nat least event-driven server applications usually benefit greatly from using threads.\n"
                },
                {
                    "name": "The World of Threading",
                    "content": "Even though lots of documents exists which describe and define the world of threading, to un‐\nderstand Pth, you need only basic knowledge about threading. The following definitions of\nthread-related terms should at least help you understand thread programming enough to allow\nyou to use Pth.\n\no process vs. thread\nA process on Unix systems consists of at least the following fundamental ingredients: vir‐\ntual memory table, program code, program counter, heap memory, stack memory, stack pointer,\nfile descriptor set, signal table. On every process switch, the kernel saves and restores\nthese ingredients for the individual processes. On the other hand, a thread consists of\nonly a private program counter, stack memory, stack pointer and signal table. All other in‐\ngredients, in particular the virtual memory, it shares with the other threads of the same\nprocess.\n\no kernel-space vs. user-space threading\nThreads on a Unix platform traditionally can be implemented either inside kernel-space or\nuser-space. When threads are implemented by the kernel, the thread context switches are\nperformed by the kernel without the application's knowledge. Similarly, when threads are\nimplemented in user-space, the thread context switches are performed by an application li‐\nbrary, without the kernel's knowledge. There also are hybrid threading approaches where,\ntypically, a user-space library binds one or more user-space threads to one or more kernel-\nspace threads (there usually called light-weight processes - or in short LWPs).\n\nUser-space threads are usually more portable and can perform faster and cheaper context\nswitches (for instance via swapcontext(2) or setjmp(3)/longjmp(3)) than kernel based\nthreads. On the other hand, kernel-space threads can take advantage of multiprocessor ma‐\nchines and don't have any inherent I/O blocking problems. Kernel-space threads are usually\nscheduled in preemptive way side-by-side with the underlying processes. User-space threads\non the other hand use either preemptive or non-preemptive scheduling.\n\no preemptive vs. non-preemptive thread scheduling\nIn preemptive scheduling, the scheduler lets a thread execute until a blocking situation\noccurs (usually a function call which would block) or the assigned timeslice elapses. Then\nit detracts control from the thread without a chance for the thread to object. This is usu‐\nally realized by interrupting the thread through a hardware interrupt signal (for kernel-\nspace threads) or a software interrupt signal (for user-space threads), like \"SIGALRM\" or\n\"SIGVTALRM\". In non-preemptive scheduling, once a thread received control from the sched‐\nuler it keeps it until either a blocking situation occurs (again a function call which\nwould block and instead switches back to the scheduler) or the thread explicitly yields\ncontrol back to the scheduler in a cooperative way.\n\no concurrency vs. parallelism\nConcurrency exists when at least two threads are in progress at the same time. Parallelism\narises when at least two threads are executing simultaneously. Real parallelism can be only\nachieved on multiprocessor machines, of course. But one also usually speaks of parallelism\nor high concurrency in the context of preemptive thread scheduling and of low concurrency\nin the context of non-preemptive thread scheduling.\n"
                },
                {
                    "name": "o responsiveness",
                    "content": "The responsiveness of a system can be described by the user visible delay until the system\nresponses to an external request. When this delay is small enough and the user doesn't rec‐\nognize a noticeable delay, the responsiveness of the system is considered good. When the\nuser recognizes or is even annoyed by the delay, the responsiveness of the system is con‐\nsidered bad.\n\no reentrant, thread-safe and asynchronous-safe functions\nA reentrant function is one that behaves correctly if it is called simultaneously by sev‐\neral threads and then also executes simultaneously.  Functions that access global state,\nsuch as memory or files, of course, need to be carefully designed in order to be reentrant.\nTwo traditional approaches to solve these problems are caller-supplied states and thread-\nspecific data.\n\nThread-safety is the avoidance of data races, i.e., situations in which data is set to ei‐\nther correct or incorrect value depending upon the (unpredictable) order in which multiple\nthreads access and modify the data. So a function is thread-safe when it still behaves se‐\nmantically correct when called simultaneously by several threads (it is not required that\nthe functions also execute simultaneously). The traditional approach to achieve thread-\nsafety is to wrap a function body with an internal mutual exclusion lock (aka `mutex'). As\nyou should recognize, reentrant is a stronger attribute than thread-safe, because it is\nharder to achieve and results especially in no run-time contention between threads. So, a\nreentrant function is always thread-safe, but not vice versa.\n\nAdditionally there is a related attribute for functions named asynchronous-safe, which\ncomes into play in conjunction with signal handlers. This is very related to the problem of\nreentrant functions. An asynchronous-safe function is one that can be called safe and with‐\nout side-effects from within a signal handler context. Usually very few functions are of\nthis type, because an application is very restricted in what it can perform from within a\nsignal handler (especially what system functions it is allowed to call). The reason mainly\nis, because only a few system functions are officially declared by POSIX as guaranteed to\nbe asynchronous-safe. Asynchronous-safe functions usually have to be already reentrant.\n"
                },
                {
                    "name": "User-Space Threads",
                    "content": "User-space threads can be implemented in various way. The two traditional approaches are:\n"
                },
                {
                    "name": "1. Matrix-based explicit dispatching between small units of execution:",
                    "content": "Here the global procedures of the application are split into small execution units (each\nis required to not run for more than a few milliseconds) and those units are implemented\nby separate functions.  Then a global matrix is defined which describes the execution (and\nperhaps even dependency) order of these functions. The main server procedure then just\ndispatches between these units by calling one function after each other controlled by this\nmatrix. The threads are created by more than one jump-trail through this matrix and by\nswitching between these jump-trails controlled by corresponding occurred events.\n\nThis approach gives the best possible performance, because one can fine-tune the threads\nof execution by adjusting the matrix, and the scheduling is done explicitly by the appli‐\ncation itself. It is also very portable, because the matrix is just an ordinary data\nstructure, and functions are a standard feature of ANSI C.\n\nThe disadvantage of this approach is that it is complicated to write large applications\nwith this approach, because in those applications one quickly gets hundreds(!) of execu‐\ntion units and the control flow inside such an application is very hard to understand (be‐\ncause it is interrupted by function borders and one always has to remember the global dis‐\npatching matrix to follow it). Additionally, all threads operate on the same execution\nstack. Although this saves memory, it is often nasty, because one cannot switch between\nthreads in the middle of a function. Thus the scheduling borders are the function borders.\n"
                },
                {
                    "name": "2. Context-based implicit scheduling between threads of execution:",
                    "content": "Here the idea is that one programs the application as with forked processes, i.e., one\nspawns a thread of execution and this runs from the begin to the end without an inter‐\nrupted control flow. But the control flow can be still interrupted - even in the middle of\na function.  Actually in a preemptive way, similar to what the kernel does for the heavy-\nweight processes, i.e., every few milliseconds the user-space scheduler switches between\nthe threads of execution. But the thread itself doesn't recognize this and usually (except\nfor synchronization issues) doesn't have to care about this.\n\nThe advantage of this approach is that it's very easy to program, because the control flow\nand context of a thread directly follows a procedure without forced interrupts through\nfunction borders.  Additionally, the programming is very similar to a traditional and well\nunderstood fork(2) based approach.\n\nThe disadvantage is that although the general performance is increased, compared to using\napproaches based on heavy-weight processes, it is decreased compared to the matrix-ap‐\nproach above. Because the implicit preemptive scheduling does usually a lot more context\nswitches (every user-space context switch costs some overhead even when it is a lot\ncheaper than a kernel-level context switch) than the explicit cooperative/non-preemptive\nscheduling.  Finally, there is no really portable POSIX/ANSI-C based way to implement\nuser-space preemptive threading. Either the platform already has threads, or one has to\nhope that some semi-portable package exists for it. And even those semi-portable packages\nusually have to deal with assembler code and other nasty internals and are not easy to\nport to forthcoming platforms.\n\nSo, in short: the matrix-dispatching approach is portable and fast, but nasty to program. The\nthread scheduling approach is easy to program, but suffers from synchronization and portabil‐\nity problems caused by its preemptive nature.\n"
                },
                {
                    "name": "The Compromise of Pth",
                    "content": "But why not combine the good aspects of both approaches while avoiding their bad aspects?\nThat's the goal of Pth. Pth implements easy-to-program threads of execution, but avoids the\nproblems of preemptive scheduling by using non-preemptive scheduling instead.\n\nThis sounds like, and is, a useful approach. Nevertheless, one has to keep the implications\nof non-preemptive thread scheduling in mind when working with Pth. The following list summa‐\nrizes a few essential points:\n\no Pth provides maximum portability, but NOT the fanciest features.\n\nThis is, because it uses a nifty and portable POSIX/ANSI-C approach for thread creation\n(and this way doesn't require any platform dependent assembler hacks) and schedules the\nthreads in non-preemptive way (which doesn't require unportable facilities like \"SIGV‐\nTALRM\"). On the other hand, this way not all fancy threading features can be implemented.\nNevertheless the available facilities are enough to provide a robust and full-featured\nthreading system.\n"
                },
                {
                    "name": "o Pth increases the responsiveness and concurrency of an event-driven application, but NOT",
                    "content": "the concurrency of number-crunching applications.\n\nThe reason is the non-preemptive scheduling. Number-crunching applications usually require\npreemptive scheduling to achieve concurrency because of their long CPU bursts. For them,\nnon-preemptive scheduling (even together with explicit yielding) provides only the old con‐\ncept of `coroutines'. On the other hand, event driven applications benefit greatly from\nnon-preemptive scheduling. They have only short CPU bursts and lots of events to wait on,\nand this way run faster under non-preemptive scheduling because no unnecessary context\nswitching occurs, as it is the case for preemptive scheduling. That's why Pth is mainly in‐\ntended for server type applications, although there is no technical restriction.\n\no Pth requires thread-safe functions, but NOT reentrant functions.\n\nThis nice fact exists again because of the nature of non-preemptive scheduling, where a\nfunction isn't interrupted and this way cannot be reentered before it returned. This is a\ngreat portability benefit, because thread-safety can be achieved more easily than reen‐\ntrance possibility. Especially this means that under Pth more existing third-party li‐\nbraries can be used without side-effects than it's the case for other threading systems.\n\no Pth doesn't require any kernel support, but can NOT benefit from multiprocessor machines.\n\nThis means that Pth runs on almost all Unix kernels, because the kernel does not need to be\naware of the Pth threads (because they are implemented entirely in user-space). On the\nother hand, it cannot benefit from the existence of multiprocessors, because for this, ker‐\nnel support would be needed. In practice, this is no problem, because multiprocessor sys‐\ntems are rare, and portability is almost more important than highest concurrency.\n"
                },
                {
                    "name": "The life cycle of a thread",
                    "content": "To understand the Pth Application Programming Interface (API), it helps to first understand\nthe life cycle of a thread in the Pth threading system. It can be illustrated with the fol‐\nlowing directed graph:\n\nNEW\n⎪\nV\n+---> READY ---+\n⎪       ^      ⎪\n⎪       ⎪      V\nWAITING <--+-- RUNNING\n⎪\n:              V\nSUSPENDED       DEAD\n\nWhen a new thread is created, it is moved into the NEW queue of the scheduler. On the next\ndispatching for this thread, the scheduler picks it up from there and moves it to the READY\nqueue. This is a queue containing all threads which want to perform a CPU burst. There they\nare queued in priority order. On each dispatching step, the scheduler always removes the\nthread with the highest priority only. It then increases the priority of all remaining\nthreads by 1, to prevent them from `starving'.\n\nThe thread which was removed from the READY queue is the new RUNNING thread (there is always\njust one RUNNING thread, of course). The RUNNING thread is assigned execution control. After\nthis thread yields execution (either explicitly by yielding execution or implicitly by call‐\ning a function which would block) there are three possibilities: Either it has terminated,\nthen it is moved to the DEAD queue, or it has events on which it wants to wait, then it is\nmoved into the WAITING queue. Else it is assumed it wants to perform more CPU bursts and im‐\nmediately enters the READY queue again.\n\nBefore the next thread is taken out of the READY queue, the WAITING queue is checked for\npending events. If one or more events occurred, the threads that are waiting on them are im‐\nmediately moved to the READY queue.\n\nThe purpose of the NEW queue has to do with the fact that in Pth a thread never directly\nswitches to another thread. A thread always yields execution to the scheduler and the sched‐\nuler dispatches to the next thread. So a freshly spawned thread has to be kept somewhere un‐\ntil the scheduler gets a chance to pick it up for scheduling. That is what the NEW queue is\nfor.\n\nThe purpose of the DEAD queue is to support thread joining. When a thread is marked to be un‐\njoinable, it is directly kicked out of the system after it terminated. But when it is join‐\nable, it enters the DEAD queue. There it remains until another thread joins it.\n\nFinally, there is a special separated queue named SUSPENDED, to where threads can be manually\nmoved from the NEW, READY or WAITING queues by the application. The purpose of this special\nqueue is to temporarily absorb suspended threads until they are again resumed by the applica‐\ntion. Suspended threads do not cost scheduling or event handling resources, because they are\ntemporarily completely out of the scheduler's scope. If a thread is resumed, it is moved back\nto the queue from where it originally came and this way again enters the schedulers scope.\n"
                },
                {
                    "name": "APPLICATION PROGRAMMING INTERFACE (API)",
                    "content": "In the following the Pth Application Programming Interface (API) is discussed in detail. With\nthe knowledge given above, it should now be easy to understand how to program threads with\nthis API. In good Unix tradition, Pth functions use special return values (\"NULL\" in pointer\ncontext, \"FALSE\" in boolean context and \"-1\" in integer context) to indicate an error condi‐\ntion and set (or pass through) the \"errno\" system variable to pass more details about the er‐\nror to the caller.\n"
                },
                {
                    "name": "Global Library Management",
                    "content": "The following functions act on the library as a whole.  They are used to initialize and shut‐\ndown the scheduler and fetch information from it.\n\nint pthinit(void);\nThis initializes the Pth library. It has to be the first Pth API function call in an ap‐\nplication, and is mandatory. It's usually done at the begin of the main() function of the\napplication. This implicitly spawns the internal scheduler thread and transforms the sin‐\ngle execution unit of the current process into a thread (the `main' thread). It returns\n\"TRUE\" on success and \"FALSE\" on error.\n\nint pthkill(void);\nThis kills the Pth library. It should be the last Pth API function call in an applica‐\ntion, but is not really required. It's usually done at the end of the main function of\nthe application. At least, it has to be called from within the main thread. It implicitly\nkills all threads and transforms back the calling thread into the single execution unit\nof the underlying process.  The usual way to terminate a Pth application is either a sim‐\nple `\"pthexit(0);\"' in the main thread (which waits for all other threads to terminate,\nkills the threading system and then terminates the process) or a `\"pthkill(); exit(0)\"'\n(which immediately kills the threading system and terminates the process). The pthkill()\nreturn immediately with a return code of \"FALSE\" if it is not called from within the main\nthread. Else it kills the threading system and returns \"TRUE\".\n\nlong pthctrl(unsigned long query, ...);\nThis is a generalized query/control function for the Pth library.  The argument query is\na bitmask formed out of one or more \"PTHCTRL\"XXXX queries. Currently the following\nqueries are supported:\n\n\"PTHCTRLGETTHREADS\"\nThis returns the total number of threads currently in existence.  This query actually\nis formed out of the combination of queries for threads in a particular state, i.e.,\nthe \"PTHCTRLGETTHREADS\" query is equal to the OR-combination of all the following\nspecialized queries:\n\n\"PTHCTRLGETTHREADSNEW\" for the number of threads in the new queue (threads created\nvia pthspawn(3) but still not scheduled once), \"PTHCTRLGETTHREADSREADY\" for the\nnumber of threads in the ready queue (threads who want to do CPU bursts),\n\"PTHCTRLGETTHREADSRUNNING\" for the number of running threads (always just one\nthread!), \"PTHCTRLGETTHREADSWAITING\" for the number of threads in the waiting\nqueue (threads waiting for events), \"PTHCTRLGETTHREADSSUSPENDED\" for the number of\nthreads in the suspended queue (threads waiting to be resumed) and \"PTHCTRLGET‐\nTHREADSDEAD\" for the number of threads in the new queue (terminated threads waiting\nfor a join).\n\n\"PTHCTRLGETAVLOAD\"\nThis requires a second argument of type `\"float *\"' (pointer to a floating point\nvariable).  It stores a floating point value describing the exponential averaged load\nof the scheduler in this variable. The load is a function from the number of threads\nin the ready queue of the schedulers dispatching unit.  So a load around 1.0 means\nthere is only one ready thread (the standard situation when the application has no\nhigh load). A higher load value means there a more threads ready who want to do CPU\nbursts. The average load value updates once per second only. The return value for\nthis query is always 0.\n\n\"PTHCTRLGETPRIO\"\nThis requires a second argument of type `\"ptht\"' which identifies a thread.  It re‐\nturns the priority (ranging from \"PTHPRIOMIN\" to \"PTHPRIOMAX\") of the given\nthread.\n\n\"PTHCTRLGETNAME\"\nThis requires a second argument of type `\"ptht\"' which identifies a thread. It re‐\nturns the name of the given thread, i.e., the return value of pthctrl(3) should be\ncasted to a `\"char *\"'.\n\n\"PTHCTRLDUMPSTATE\"\nThis requires a second argument of type `\"FILE *\"' to which a summary of the internal\nPth library state is written to. The main information which is currently written out\nis the current state of the thread pool.\n\n\"PTHCTRLFAVOURNEW\"\nThis requires a second argument of type `\"int\"' which specified whether the GNU Pth\nscheduler favours new threads on startup, i.e., whether they are moved from the new\nqueue to the top (argument is \"TRUE\") or middle (argument is \"FALSE\") of the ready\nqueue. The default is to favour new threads to make sure they do not starve already\nat startup, although this slightly violates the strict priority based scheduling.\n\nThe function returns \"-1\" on error.\n\nlong pthversion(void);\nThis function returns a hex-value `0xVRRTLL' which describes the current Pth library ver‐\nsion. V is the version, RR the revisions, LL the level and T the type of the level (al‐\nphalevel=0, betalevel=1, patchlevel=2, etc). For instance Pth version 1.0b1 is encoded as\n0x100101.  The reason for this unusual mapping is that this way the version number is\nsteadily increasing. The same value is also available under compile time as \"PTHVER‐\nSION\".\n"
                },
                {
                    "name": "Thread Attribute Handling",
                    "content": "Attribute objects are used in Pth for two things: First stand-alone/unbound attribute objects\nare used to store attributes for to be spawned threads.  Bounded attribute objects are used\nto modify attributes of already existing threads. The following attribute fields exists in\nattribute objects:\n\n\"PTHATTRPRIO\" (read-write) [\"int\"]\nThread Priority between \"PTHPRIOMIN\" and \"PTHPRIOMAX\".  The default is\n\"PTHPRIOSTD\".\n\n\"PTHATTRNAME\" (read-write) [\"char *\"]\nName of thread (up to 40 characters are stored only), mainly for debugging purposes.\n\n\"PTHATTRDISPATCHES\" (read-write) [\"int\"]\nIn bounded attribute objects, this field is incremented every time the context is\nswitched to the associated thread.\n\n\"PTHATTRJOINABLE\" (read-write> [\"int\"]\nThe thread detachment type, \"TRUE\" indicates a joinable thread, \"FALSE\" indicates a de‐\ntached thread. When a thread is detached, after termination it is immediately kicked out\nof the system instead of inserted into the dead queue.\n\n\"PTHATTRCANCELSTATE\" (read-write) [\"unsigned int\"]\nThe thread cancellation state, i.e., a combination of \"PTHCANCELENABLE\" or \"PTHCAN‐\nCELDISABLE\" and \"PTHCANCELDEFERRED\" or \"PTHCANCELASYNCHRONOUS\".\n\n\"PTHATTRSTACKSIZE\" (read-write) [\"unsigned int\"]\nThe thread stack size in bytes. Use lower values than 64 KB with great care!\n\n\"PTHATTRSTACKADDR\" (read-write) [\"char *\"]\nA pointer to the lower address of a chunk of malloc(3)'ed memory for the stack.\n\n\"PTHATTRTIMESPAWN\" (read-only) [\"pthtimet\"]\nThe time when the thread was spawned.  This can be queried only when the attribute object\nis bound to a thread.\n\n\"PTHATTRTIMELAST\" (read-only) [\"pthtimet\"]\nThe time when the thread was last dispatched.  This can be queried only when the attri‐\nbute object is bound to a thread.\n\n\"PTHATTRTIMERAN\" (read-only) [\"pthtimet\"]\nThe total time the thread was running.  This can be queried only when the attribute ob‐\nject is bound to a thread.\n\n\"PTHATTRSTARTFUNC\" (read-only) [\"void *(*)(void *)\"]\nThe thread start function.  This can be queried only when the attribute object is bound\nto a thread.\n\n\"PTHATTRSTARTARG\" (read-only) [\"void *\"]\nThe thread start argument.  This can be queried only when the attribute object is bound\nto a thread.\n\n\"PTHATTRSTATE\" (read-only) [\"pthstatet\"]\nThe scheduling state of the thread, i.e., either \"PTHSTATENEW\", \"PTHSTATEREADY\",\n\"PTHSTATEWAITING\", or \"PTHSTATEDEAD\" This can be queried only when the attribute ob‐\nject is bound to a thread.\n\n\"PTHATTREVENTS\" (read-only) [\"ptheventt\"]\nThe event ring the thread is waiting for.  This can be queried only when the attribute\nobject is bound to a thread.\n\n\"PTHATTRBOUND\" (read-only) [\"int\"]\nWhether the attribute object is bound (\"TRUE\") to a thread or not (\"FALSE\").\n\nThe following API functions can be used to handle the attribute objects:\n\npthattrt pthattrof(ptht tid);\nThis returns a new attribute object bound to thread tid.  Any queries on this object di‐\nrectly fetch attributes from tid. And attribute modifications directly change tid. Use\nsuch attribute objects to modify existing threads.\n\npthattrt pthattrnew(void);\nThis returns a new unbound attribute object. An implicit pthattrinit() is done on it.\nAny queries on this object just fetch stored attributes from it.  And attribute modifica‐\ntions just change the stored attributes.  Use such attribute objects to pre-configure at‐\ntributes for to be spawned threads.\n\nint pthattrinit(pthattrt attr);\nThis initializes an attribute object attr to the default values: \"PTHATTRPRIO\" :=\n\"PTHPRIOSTD\", \"PTHATTRNAME\" := `\"unknown\"', \"PTHATTRDISPATCHES\" := 0,\n\"PTHATTRJOINABLE\" := \"TRUE\", \"PTHATTRCANCELSTATE\" := \"PTHCANCELDEFAULT\",\n\"PTHATTRSTACKSIZE\" := 64*1024 and \"PTHATTRSTACKADDR\" := \"NULL\". All other\n\"PTHATTR*\" attributes are read-only attributes and don't receive default values in\nattr, because they exists only for bounded attribute objects.\n\nint pthattrset(pthattrt attr, int field, ...);\nThis sets the attribute field field in attr to a value specified as an additional argu‐\nment on the variable argument list. The following attribute fields and argument pairs can\nbe used:\n\nPTHATTRPRIO           int\nPTHATTRNAME           char *\nPTHATTRDISPATCHES     int\nPTHATTRJOINABLE       int\nPTHATTRCANCELSTATE   unsigned int\nPTHATTRSTACKSIZE     unsigned int\nPTHATTRSTACKADDR     char *\n\nint pthattrget(pthattrt attr, int field, ...);\nThis retrieves the attribute field field in attr and stores its value in the variable\nspecified through a pointer in an additional argument on the variable argument list. The\nfollowing fields and argument pairs can be used:\n\nPTHATTRPRIO           int *\nPTHATTRNAME           char\nPTHATTRDISPATCHES     int *\nPTHATTRJOINABLE       int *\nPTHATTRCANCELSTATE   unsigned int *\nPTHATTRSTACKSIZE     unsigned int *\nPTHATTRSTACKADDR     char\nPTHATTRTIMESPAWN     pthtimet *\nPTHATTRTIMELAST      pthtimet *\nPTHATTRTIMERAN       pthtimet *\nPTHATTRSTARTFUNC     void *()(void *)\nPTHATTRSTARTARG      void\nPTHATTRSTATE          pthstatet *\nPTHATTREVENTS         ptheventt *\nPTHATTRBOUND          int *\n\nint pthattrdestroy(pthattrt attr);\nThis destroys a attribute object attr. After this attr is no longer a valid attribute ob‐\nject.\n"
                },
                {
                    "name": "Thread Control",
                    "content": "The following functions control the threading itself and make up the main API of the Pth li‐\nbrary.\n\nptht pthspawn(pthattrt attr, void *(*entry)(void *), void *arg);\nThis spawns a new thread with the attributes given in attr (or \"PTHATTRDEFAULT\" for de‐\nfault attributes - which means that thread priority, joinability and cancel state are in‐\nherited from the current thread) with the starting point at routine entry; the dispatch\ncount is not inherited from the current thread if attr is not specified - rather, it is\ninitialized to zero.  This entry routine is called as `pthexit(entry(arg))' inside the\nnew thread unit, i.e., entry's return value is fed to an implicit pthexit(3). So the\nthread can also exit by just returning. Nevertheless the thread can also exit explicitly\nat any time by calling pthexit(3). But keep in mind that calling the POSIX function\nexit(3) still terminates the complete process and not just the current thread.\n\nThere is no Pth-internal limit on the number of threads one can spawn, except the limit\nimplied by the available virtual memory. Pth internally keeps track of thread in dynamic\ndata structures. The function returns \"NULL\" on error.\n\nint pthonce(pthoncet *ctrlvar, void (*func)(void *), void *arg);\nThis is a convenience function which uses a control variable of type \"pthoncet\" to make\nsure a constructor function func is called only once as `func(arg)' in the system. In\nother words: Only the first call to pthonce(3) by any thread in the system succeeds. The\nvariable referenced via ctrlvar should be declared as `\"pthoncet\" variable-name =\n\"PTHONCEINIT\";' before calling this function.\n\nptht pthself(void);\nThis just returns the unique thread handle of the currently running thread.  This handle\nitself has to be treated as an opaque entity by the application.  It's usually used as an\nargument to other functions who require an argument of type \"ptht\".\n\nint pthsuspend(ptht tid);\nThis suspends a thread tid until it is manually resumed again via pthresume(3). For\nthis, the thread is moved to the SUSPENDED queue and this way is completely out of the\nscheduler's event handling and thread dispatching scope. Suspending the current thread is\nnot allowed.  The function returns \"TRUE\" on success and \"FALSE\" on errors.\n\nint pthresume(ptht tid);\nThis function resumes a previously suspended thread tid, i.e. tid has to stay on the SUS‐‐\nPENDED queue. The thread is moved to the NEW, READY or WAITING queue (dependent on what\nits state was when the pthsuspend(3) call were made) and this way again enters the event\nhandling and thread dispatching scope of the scheduler. The function returns \"TRUE\" on\nsuccess and \"FALSE\" on errors.\n\nint pthraise(ptht tid, int sig)\nThis function raises a signal for delivery to thread tid only.  When one just raises a\nsignal via raise(3) or kill(2), its delivered to an arbitrary thread which has this sig‐\nnal not blocked.  With pthraise(3) one can send a signal to a thread and its guarantees\nthat only this thread gets the signal delivered. But keep in mind that nevertheless the\nsignals action is still configured process-wide.  When sig is 0 plain thread checking is\nperformed, i.e., `\"pthraise(tid, 0)\"' returns \"TRUE\" when thread tid still exists in the\nPTH system but doesn't send any signal to it.\n\nint pthyield(ptht tid);\nThis explicitly yields back the execution control to the scheduler thread.  Usually the\nexecution is implicitly transferred back to the scheduler when a thread waits for an\nevent. But when a thread has to do larger CPU bursts, it can be reasonable to interrupt\nit explicitly by doing a few pthyield(3) calls to give other threads a chance to exe‐\ncute, too.  This obviously is the cooperating part of Pth.  A thread has not to yield ex‐\necution, of course. But when you want to program a server application with good response\ntimes the threads should be cooperative, i.e., when they should split their CPU bursts\ninto smaller units with this call.\n\nUsually one specifies tid as \"NULL\" to indicate to the scheduler that it can freely de‐\ncide which thread to dispatch next.  But if one wants to indicate to the scheduler that a\nparticular thread should be favored on the next dispatching step, one can specify this\nthread explicitly. This allows the usage of the old concept of coroutines where a\nthread/routine switches to a particular cooperating thread. If tid is not \"NULL\" and\npoints to a new or ready thread, it is guaranteed that this thread receives execution\ncontrol on the next dispatching step. If tid is in a different state (that is, not in\n\"PTHSTATENEW\" or \"PTHSTATEREADY\") an error is reported.\n\nThe function usually returns \"TRUE\" for success and only \"FALSE\" (with \"errno\" set to\n\"EINVAL\") if tid specified an invalid or still not new or ready thread.\n\nint pthnap(pthtimet naptime);\nThis functions suspends the execution of the current thread until naptime is elapsed.\nnaptime is of type \"pthtimet\" and this way has theoretically a resolution of one mi‐\ncrosecond. In practice you should neither rely on this nor that the thread is awakened\nexactly after naptime has elapsed. It's only guarantees that the thread will sleep at\nleast naptime. But because of the non-preemptive nature of Pth it can last longer (when\nanother thread kept the CPU for a long time). Additionally the resolution is dependent of\nthe implementation of timers by the operating system and these usually have only a reso‐\nlution of 10 microseconds or larger. But usually this isn't important for an application\nunless it tries to use this facility for real time tasks.\n\nint pthwait(ptheventt ev);\nThis is the link between the scheduler and the event facility (see below for the various\nptheventxxx() functions). It's modeled like select(2), i.e., one gives this function\none or more events (in the event ring specified by ev) on which the current thread wants\nto wait. The scheduler awakes the thread when one ore more of them occurred or failed af‐\nter tagging them as such. The ev argument is a pointer to an event ring which isn't\nchanged except for the tagging. pthwait(3) returns the number of occurred or failed\nevents and the application can use ptheventstatus(3) to test which events occurred or\nfailed.\n\nint pthcancel(ptht tid);\nThis cancels a thread tid. How the cancellation is done depends on the cancellation state\nof tid which the thread can configure itself. When its state is \"PTHCANCELDISABLE\" a\ncancellation request is just made pending.  When it is \"PTHCANCELENABLE\" it depends on\nthe cancellation type what is performed. When its \"PTHCANCELDEFERRED\" again the cancel‐\nlation request is just made pending. But when its \"PTHCANCELASYNCHRONOUS\" the thread is\nimmediately canceled before pthcancel(3) returns. The effect of a thread cancellation is\nequal to implicitly forcing the thread to call `\"pthexit(PTHCANCELED)\"' at one of his\ncancellation points.  In Pth thread enter a cancellation point either explicitly via\npthcancelpoint(3) or implicitly by waiting for an event.\n\nint pthabort(ptht tid);\nThis is the cruel way to cancel a thread tid. When it's already dead and waits to be\njoined it just joins it (via `\"pthjoin(\"tid\", NULL)\"') and this way kicks it out of the\nsystem.  Else it forces the thread to be not joinable and to allow asynchronous cancella‐\ntion and then cancels it via `\"pthcancel(\"tid\")\"'.\n\nint pthjoin(ptht tid, void value);\nThis joins the current thread with the thread specified via tid.  It first suspends the\ncurrent thread until the tid thread has terminated. Then it is awakened and stores the\nvalue of tid's pthexit(3) call into *value (if value and not \"NULL\") and returns to the\ncaller. A thread can be joined only when it has the attribute \"PTHATTRJOINABLE\" set to\n\"TRUE\" (the default). A thread can only be joined once, i.e., after the pthjoin(3) call\nthe thread tid is completely removed from the system.\n\nvoid pthexit(void *value);\nThis terminates the current thread. Whether it's immediately removed from the system or\ninserted into the dead queue of the scheduler depends on its join type which was speci‐\nfied at spawning time. If it has the attribute \"PTHATTRJOINABLE\" set to \"FALSE\", it's\nimmediately removed and value is ignored. Else the thread is inserted into the dead queue\nand value remembered for a subsequent pthjoin(3) call by another thread.\n"
                },
                {
                    "name": "Utilities",
                    "content": "Utility functions.\n\nint pthfdmode(int fd, int mode);\nThis switches the non-blocking mode flag on file descriptor fd.  The argument mode can be\n\"PTHFDMODEBLOCK\" for switching fd into blocking I/O mode, \"PTHFDMODENONBLOCK\" for\nswitching fd into non-blocking I/O mode or \"PTHFDMODEPOLL\" for just polling the current\nmode. The current mode is returned (either \"PTHFDMODEBLOCK\" or \"PTHFDMODENONBLOCK\")\nor \"PTHFDMODEERROR\" on error. Keep in mind that since Pth 1.1 there is no longer a re‐\nquirement to manually switch a file descriptor into non-blocking mode in order to use it.\nThis is automatically done temporarily inside Pth.  Instead when you now switch a file\ndescriptor explicitly into non-blocking mode, pthread(3) or pthwrite(3) will never\nblock the current thread.\n\npthtimet pthtime(long sec, long usec);\nThis is a constructor for a \"pthtimet\" structure which is a convenient function to\navoid temporary structure values. It returns a pthtimet structure which holds the abso‐\nlute time value specified by sec and usec.\n\npthtimet pthtimeout(long sec, long usec);\nThis is a constructor for a \"pthtimet\" structure which is a convenient function to\navoid temporary structure values.  It returns a pthtimet structure which holds the ab‐\nsolute time value calculated by adding sec and usec to the current time.\n\nSfdisct *pthsfiodisc(void);\nThis functions is always available, but only reasonably usable when Pth was built with\nSfio support (\"--with-sfio\" option) and \"PTHEXTSFIO\" is then defined by \"pth.h\". It is\nuseful for applications which want to use the comprehensive Sfio I/O library with the Pth\nthreading library. Then this function can be used to get an Sfio discipline structure\n(\"Sfdisct\") which can be pushed onto Sfio streams (\"Sfiot\") in order to let this stream\nuse pthread(3)/pthwrite(2) instead of read(2)/write(2). The benefit is that this way\nI/O on the Sfio stream does only block the current thread instead of the whole process.\nThe application has to free(3) the \"Sfdisct\" structure when it is no longer needed. The\nSfio package can be found at http://www.research.att.com/sw/tools/sfio/.\n"
                },
                {
                    "name": "Cancellation Management",
                    "content": "Pth supports POSIX style thread cancellation via pthcancel(3) and the following two related\nfunctions:\n\nvoid pthcancelstate(int newstate, int *oldstate);\nThis manages the cancellation state of the current thread.  When oldstate is not \"NULL\"\nthe function stores the old cancellation state under the variable pointed to by oldstate.\nWhen newstate is not 0 it sets the new cancellation state. oldstate is created before\nnewstate is set.  A state is a combination of \"PTHCANCELENABLE\" or \"PTHCANCELDISABLE\"\nand \"PTHCANCELDEFERRED\" or \"PTHCANCELASYNCHRONOUS\".  \"PTHCANCELENABLE⎪PTHCAN‐\nCELDEFERRED\" (or \"PTHCANCELDEFAULT\") is the default state where cancellation is possi‐\nble but only at cancellation points.  Use \"PTHCANCELDISABLE\" to complete disable can‐\ncellation for a thread and \"PTHCANCELASYNCHRONOUS\" for allowing asynchronous cancella‐\ntions, i.e., cancellations which can happen at any time.\n\nvoid pthcancelpoint(void);\nThis explicitly enter a cancellation point. When the current cancellation state is\n\"PTHCANCELDISABLE\" or no cancellation request is pending, this has no side-effect and\nreturns immediately. Else it calls `\"pthexit(PTHCANCELED)\"'.\n"
                },
                {
                    "name": "Event Handling",
                    "content": "Pth has a very flexible event facility which is linked into the scheduler through the\npthwait(3) function. The following functions provide the handling of event rings.\n\nptheventt pthevent(unsigned long spec, ...);\nThis creates a new event ring consisting of a single initial event.  The type of the gen‐\nerated event is specified by spec. The following types are available:\n\n\"PTHEVENTFD\"\nThis is a file descriptor event. One or more of \"PTHUNTILFDREADABLE\", \"PTHUN‐\nTILFDWRITEABLE\" or \"PTHUNTILFDEXCEPTION\" have to be OR-ed into spec to specify\non which state of the file descriptor you want to wait.  The file descriptor itself\nhas to be given as an additional argument.  Example: `\"pthevent(PTHEVENTFD⎪PTHUN‐\nTILFDREADABLE, fd)\"'.\n\n\"PTHEVENTSELECT\"\nThis is a multiple file descriptor event modeled directly after the select(2) call\n(actually it is also used to implement pthselect(3) internally).  It's a convenient\nway to wait for a large set of file descriptors at once and at each file descriptor\nfor a different type of state. Additionally as a nice side-effect one receives the\nnumber of file descriptors which causes the event to be occurred (using BSD seman‐\ntics, i.e., when a file descriptor occurred in two sets it's counted twice). The ar‐\nguments correspond directly to the select(2) function arguments except that there is\nno timeout argument (because timeouts already can be handled via \"PTHEVENTTIME\"\nevents).\n\nExample: `\"pthevent(PTHEVENTSELECT, &rc, nfd, rfds, wfds, efds)\"' where \"rc\" has\nto be of type `\"int *\"', \"nfd\" has to be of type `\"int\"' and \"rfds\", \"wfds\" and\n\"efds\" have to be of type `\"fdset *\"' (see select(2)). The number of occurred file\ndescriptors are stored in \"rc\".\n\n\"PTHEVENTSIGS\"\nThis is a signal set event. The two additional arguments have to be a pointer to a\nsignal set (type `\"sigsett *\"') and a pointer to a signal number variable (type\n`\"int *\"').  This event waits until one of the signals in the signal set occurred.\nAs a result the occurred signal number is stored in the second additional argument.\nKeep in mind that the Pth scheduler doesn't block signals automatically.  So when you\nwant to wait for a signal with this event you've to block it via sigprocmask(2) or it\nwill be delivered without your notice. Example: `\"sigemptyset(&set); sigaddset(&set,\nSIGINT); pthevent(PTHEVENTSIG, &set, &sig);\"'.\n\n\"PTHEVENTTIME\"\nThis is a time point event. The additional argument has to be of type \"pthtimet\"\n(usually on-the-fly generated via pthtime(3)). This events waits until the specified\ntime point has elapsed. Keep in mind that the value is an absolute time point and not\nan offset. When you want to wait for a specified amount of time, you've to add the\ncurrent time to the offset (usually on-the-fly achieved via pthtimeout(3)).  Exam‐\nple: `\"pthevent(PTHEVENTTIME, pthtimeout(2,0))\"'.\n\n\"PTHEVENTMSG\"\nThis is a message port event. The additional argument has to be of type \"pthmsg‐\nportt\". This events waits until one or more messages were received on the specified\nmessage port.  Example: `\"pthevent(PTHEVENTMSG, mp)\"'.\n\n\"PTHEVENTTID\"\nThis is a thread event. The additional argument has to be of type \"ptht\".  One of\n\"PTHUNTILTIDNEW\", \"PTHUNTILTIDREADY\", \"PTHUNTILTIDWAITING\" or \"PTHUN‐\nTILTIDDEAD\" has to be OR-ed into spec to specify on which state of the thread you\nwant to wait.  Example: `\"pthevent(PTHEVENTTID⎪PTHUNTILTIDDEAD, tid)\"'.\n\n\"PTHEVENTFUNC\"\nThis is a custom callback function event. Three additional arguments have to be given\nwith the following types: `\"int (*)(void *)\"', `\"void *\"' and `\"pthtimet\"'. The\nfirst is a function pointer to a check function and the second argument is a user-\nsupplied context value which is passed to this function. The scheduler calls this\nfunction on a regular basis (on his own scheduler stack, so be very careful!) and the\nthread is kept sleeping while the function returns \"FALSE\". Once it returned \"TRUE\"\nthe thread will be awakened. The check interval is defined by the third argument,\ni.e., the check function is polled again not until this amount of time elapsed. Exam‐\nple: `\"pthevent(PTHEVENTFUNC, func, arg, pthtime(0,500000))\"'.\n\nunsigned long ptheventtypeof(ptheventt ev);\nThis returns the type of event ev. It's a combination of the describing \"PTHEVENTXX\"\nand \"PTHUNTILXX\" value. This is especially useful to know which arguments have to be\nsupplied to the ptheventextract(3) function.\n\nint ptheventextract(ptheventt ev, ...);\nWhen pthevent(3) is treated like sprintf(3), then this function is sscanf(3), i.e., it\nis the inverse operation of pthevent(3). This means that it can be used to extract the\ningredients of an event.  The ingredients are stored into variables which are given as\npointers on the variable argument list.  Which pointers have to be present depends on the\nevent type and has to be determined by the caller before via ptheventtypeof(3).\n\nTo make it clear, when you constructed ev via `\"ev = pthevent(PTHEVENTFD, fd);\"' you\nhave to extract it via `\"ptheventextract(ev, &fd)\"', etc. For multiple arguments of an\nevent the order of the pointer arguments is the same as for pthevent(3). But always keep\nin mind that you have to always supply pointers to variables and these variables have to\nbe of the same type as the argument of pthevent(3) required.\n\nptheventt ptheventconcat(ptheventt ev, ...);\nThis concatenates one or more additional event rings to the event ring ev and returns ev.\nThe end of the argument list has to be marked with a \"NULL\" argument. Use this function\nto create real events rings out of the single-event rings created by pthevent(3).\n\nptheventt ptheventisolate(ptheventt ev);\nThis isolates the event ev from possibly appended events in the event ring.  When in ev\nonly one event exists, this returns \"NULL\". When remaining events exists, they form a new\nevent ring which is returned.\n\nptheventt ptheventwalk(ptheventt ev, int direction);\nThis walks to the next (when direction is \"PTHWALKNEXT\") or previews (when direction is\n\"PTHWALKPREV\") event in the event ring ev and returns this new reached event. Addition‐\nally \"PTHUNTILOCCURRED\" can be OR-ed into direction to walk to the next/previous oc‐\ncurred event in the ring ev.\n\npthstatust ptheventstatus(ptheventt ev);\nThis returns the status of event ev. This is a fast operation because only a tag on ev is\nchecked which was either set or still not set by the scheduler. In other words: This\ndoesn't check the event itself, it just checks the last knowledge of the scheduler. The\npossible returned status codes are: \"PTHSTATUSPENDING\" (event is still pending),\n\"PTHSTATUSOCCURRED\" (event successfully occurred), \"PTHSTATUSFAILED\" (event failed).\n\nint ptheventfree(ptheventt ev, int mode);\nThis deallocates the event ev (when mode is \"PTHFREETHIS\") or all events appended to\nthe event ring under ev (when mode is \"PTHFREEALL\").\n"
                },
                {
                    "name": "Key-Based Storage",
                    "content": "The following functions provide thread-local storage through unique keys similar to the POSIX\nPthread API. Use this for thread specific global data.\n\nint pthkeycreate(pthkeyt *key, void (*func)(void *));\nThis created a new unique key and stores it in key.  Additionally func can specify a de‐\nstructor function which is called on the current threads termination with the key.\n\nint pthkeydelete(pthkeyt key);\nThis explicitly destroys a key key.\n\nint pthkeysetdata(pthkeyt key, const void *value);\nThis stores value under key.\n\nvoid *pthkeygetdata(pthkeyt key);\nThis retrieves the value under key.\n"
                },
                {
                    "name": "Message Port Communication",
                    "content": "The following functions provide message ports which can be used for efficient and flexible\ninter-thread communication.\n\npthmsgportt pthmsgportcreate(const char *name);\nThis returns a pointer to a new message port. If name name is not \"NULL\", the name can be\nused by other threads via pthmsgportfind(3) to find the message port in case they do\nnot know directly the pointer to the message port.\n\nvoid pthmsgportdestroy(pthmsgportt mp);\nThis destroys a message port mp. Before all pending messages on it are replied to their\norigin message port.\n\npthmsgportt pthmsgportfind(const char *name);\nThis finds a message port in the system by name and returns the pointer to it.\n\nint pthmsgportpending(pthmsgportt mp);\nThis returns the number of pending messages on message port mp.\n\nint pthmsgportput(pthmsgportt mp, pthmessaget *m);\nThis puts (or sends) a message m to message port mp.\n\npthmessaget *pthmsgportget(pthmsgportt mp);\nThis gets (or receives) the top message from message port mp.  Incoming messages are al‐\nways kept in a queue, so there can be more pending messages, of course.\n\nint pthmsgportreply(pthmessaget *m);\nThis replies a message m to the message port of the sender.\n"
                },
                {
                    "name": "Thread Cleanups",
                    "content": "Per-thread cleanup functions.\n\nint pthcleanuppush(void (*handler)(void *), void *arg);\nThis pushes the routine handler onto the stack of cleanup routines for the current\nthread.  These routines are called in LIFO order when the thread terminates.\n\nint pthcleanuppop(int execute);\nThis pops the top-most routine from the stack of cleanup routines for the current thread.\nWhen execute is \"TRUE\" the routine is additionally called.\n"
                },
                {
                    "name": "Process Forking",
                    "content": "The following functions provide some special support for process forking situations inside\nthe threading environment.\n\nint pthatforkpush(void (*prepare)(void *), void (*)(void *parent), void (*)(void *child),\nvoid *arg);\nThis function declares forking handlers to be called before and after pthfork(3), in the\ncontext of the thread that called pthfork(3). The prepare handler is called before\nfork(2) processing commences. The parent handler is called   after fork(2) processing\ncompletes in the parent process.  The child handler is called after fork(2) processing\ncompleted in the child process. If no handling is desired at one or more of these three\npoints, the corresponding handler can be given as \"NULL\".  Each handler is called with\narg as the argument.\n\nThe order of calls to pthatforkpush(3) is significant. The parent and child handlers\nare called in the order in which they were established by calls to pthatforkpush(3),\ni.e., FIFO. The prepare fork handlers are called in the opposite order, i.e., LIFO.\n\nint pthatforkpop(void);\nThis removes the top-most handlers on the forking handler stack which were established\nwith the last pthatforkpush(3) call. It returns \"FALSE\" when no more handlers couldn't\nbe removed from the stack.\n\npidt pthfork(void);\nThis is a variant of fork(2) with the difference that the current thread only is forked\ninto a separate process, i.e., in the parent process nothing changes while in the child\nprocess all threads are gone except for the scheduler and the calling thread. When you\nreally want to duplicate all threads in the current process you should use fork(2) di‐\nrectly. But this is usually not reasonable. Additionally this function takes care of\nforking handlers as established by pthforkpush(3).\n"
                },
                {
                    "name": "Synchronization",
                    "content": "The following functions provide synchronization support via mutual exclusion locks (mutex),\nread-write locks (rwlock), condition variables (cond) and barriers (barrier). Keep in mind\nthat in a non-preemptive threading system like Pth this might sound unnecessary at the first\nlook, because a thread isn't interrupted by the system. Actually when you have a critical\ncode section which doesn't contain any pthxxx() functions, you don't need any mutex to pro‐\ntect it, of course.\n\nBut when your critical code section contains any pthxxx() function the chance is high that\nthese temporarily switch to the scheduler. And this way other threads can make progress and\nenter your critical code section, too.  This is especially true for critical code sections\nwhich implicitly or explicitly use the event mechanism.\n\nint pthmutexinit(pthmutext *mutex);\nThis dynamically initializes a mutex variable of type `\"pthmutext\"'.  Alternatively one\ncan also use static initialization via `\"pthmutext mutex = PTHMUTEXINIT\"'.\n\nint pthmutexacquire(pthmutext *mutex, int try, ptheventt ev);\nThis acquires a mutex mutex.  If the mutex is already locked by another thread, the cur‐\nrent threads execution is suspended until the mutex is unlocked again or additionally the\nextra events in ev occurred (when ev is not \"NULL\").  Recursive locking is explicitly\nsupported, i.e., a thread is allowed to acquire a mutex more than once before its re‐\nleased. But it then also has be released the same number of times until the mutex is\nagain lockable by others.  When try is \"TRUE\" this function never suspends execution. In‐\nstead it returns \"FALSE\" with \"errno\" set to \"EBUSY\".\n\nint pthmutexrelease(pthmutext *mutex);\nThis decrements the recursion locking count on mutex and when it is zero it releases the\nmutex mutex.\n\nint pthrwlockinit(pthrwlockt *rwlock);\nThis dynamically initializes a read-write lock variable of type `\"pthrwlockt\"'.  Alter‐\nnatively one can also use static initialization via `\"pthrwlockt rwlock =\nPTHRWLOCKINIT\"'.\n\nint pthrwlockacquire(pthrwlockt *rwlock, int op, int try, ptheventt ev);\nThis acquires a read-only (when op is \"PTHRWLOCKRD\") or a read-write (when op is\n\"PTHRWLOCKRW\") lock rwlock. When the lock is only locked by other threads in read-only\nmode, the lock succeeds.  But when one thread holds a read-write lock, all locking at‐\ntempts suspend the current thread until this lock is released again. Additionally in ev\nevents can be given to let the locking timeout, etc. When try is \"TRUE\" this function\nnever suspends execution. Instead it returns \"FALSE\" with \"errno\" set to \"EBUSY\".\n\nint pthrwlockrelease(pthrwlockt *rwlock);\nThis releases a previously acquired (read-only or read-write) lock.\n\nint pthcondinit(pthcondt *cond);\nThis dynamically initializes a condition variable variable of type `\"pthcondt\"'.  Al‐\nternatively one can also use static initialization via `\"pthcondt cond =\nPTHCONDINIT\"'.\n\nint pthcondawait(pthcondt *cond, pthmutext *mutex, ptheventt ev);\nThis awaits a condition situation. The caller has to follow the semantics of the POSIX\ncondition variables: mutex has to be acquired before this function is called. The execu‐\ntion of the current thread is then suspended either until the events in ev occurred (when\nev is not \"NULL\") or cond was notified by another thread via pthcondnotify(3).  While\nthe thread is waiting, mutex is released. Before it returns mutex is reacquired.\n\nint pthcondnotify(pthcondt *cond, int broadcast);\nThis notified one or all threads which are waiting on cond.  When broadcast is \"TRUE\" all\nthread are notified, else only a single (unspecified) one.\n\nint pthbarrierinit(pthbarriert *barrier, int threshold);\nThis dynamically initializes a barrier variable of type `\"pthbarriert\"'.  Alternatively\none can also use static initialization via `\"pthbarriert barrier = PTHBAR‐\nRIERINIT(\"threadhold\")\"'.\n\nint pthbarrierreach(pthbarriert *barrier);\nThis function reaches a barrier barrier. If this is the last thread (as specified by\nthreshold on init of barrier) all threads are awakened.  Else the current thread is sus‐\npended until the last thread reached the barrier and this way awakes all threads. The\nfunction returns (beside \"FALSE\" on error) the value \"TRUE\" for any thread which neither\nreached the barrier as the first nor the last thread; \"PTHBARRIERHEADLIGHT\" for the\nthread which reached the barrier as the first thread and \"PTHBARRIERTAILLIGHT\" for the\nthread which reached the barrier as the last thread.\n"
                },
                {
                    "name": "User-Space Context",
                    "content": "The following functions provide a stand-alone sub-API for user-space context switching. It\ninternally is based on the same underlying machine context switching mechanism the threads in\nGNU Pth are based on.  Hence these functions you can use for implementing your own simple\nuser-space threads. The \"pthuctxt\" context is somewhat modeled after POSIX ucontext(3).\n\nThe time required to create (via pthuctxmake(3)) a user-space context can range from just a\nfew microseconds up to a more dramatical time (depending on the machine context switching\nmethod which is available on the platform). On the other hand, the raw performance in switch‐\ning the user-space contexts is always very good (nearly independent of the used machine con‐\ntext switching method). For instance, on an Intel Pentium-III CPU with 800Mhz running under\nFreeBSD 4 one usually achieves about 260,000 user-space context switches (via\npthuctxswitch(3)) per second.\n\nint pthuctxcreate(pthuctxt *uctx);\nThis function creates a user-space context and stores it into uctx.  There is still no\nunderlying user-space context configured. You still have to do this with\npthuctxmake(3). On success, this function returns \"TRUE\", else \"FALSE\".\n\nint pthuctxmake(pthuctxt uctx, char *skaddr, sizet sksize, const sigsett *sigmask,\nvoid (*startfunc)(void *), void *startarg, pthuctxt uctxafter);\nThis function makes a new user-space context in uctx which will operate on the run-time\nstack skaddr (which is of maximum size sksize), with the signals in sigmask blocked (if\nsigmask is not \"NULL\") and starting to execute with the call startfunc(startarg). If\nskaddr is \"NULL\", a stack is dynamically allocated. The stack size sksize has to be at\nleast 16384 (16KB). If the start function startfunc returns and uctxafter is not\n\"NULL\", an implicit user-space context switch to this context is performed. Else (if\nuctxafter is \"NULL\") the process is terminated with exit(3). This function is somewhat\nmodeled after POSIX makecontext(3). On success, this function returns \"TRUE\", else\n\"FALSE\".\n\nint pthuctxswitch(pthuctxt uctxfrom, pthuctxt uctxto);\nThis function saves the current user-space context in uctxfrom for later restoring by\nanother call to pthuctxswitch(3) and restores the new user-space context from uctxto,\nwhich previously had to be set with either a previous call to pthuctxswitch(3) or ini‐\ntially by pthuctxmake(3). This function is somewhat modeled after POSIX swapcontext(3).\nIf uctxfrom or uctxto are \"NULL\" or if uctxto contains no valid user-space context,\n\"FALSE\" is returned instead of \"TRUE\". These are the only errors possible.\n\nint pthuctxdestroy(pthuctxt uctx);\nThis function destroys the user-space context in uctx. The run-time stack associated with\nthe user-space context is deallocated only if it was not given by the application (see\nskaddr of pthuctxcreate(3)).  If uctx is \"NULL\", \"FALSE\" is returned instead of\n\"TRUE\". This is the only error possible.\n"
                },
                {
                    "name": "Generalized POSIX Replacement API",
                    "content": "The following functions are generalized replacements functions for the POSIX API, i.e., they\nare similar to the functions under `Standard POSIX Replacement API' but all have an addi‐\ntional event argument which can be used for timeouts, etc.\n\nint pthsigwaitev(const sigsett *set, int *sig, ptheventt ev);\nThis is equal to pthsigwait(3) (see below), but has an additional event argument ev.\nWhen pthsigwait(3) suspends the current threads execution it usually only uses the sig‐\nnal event on set to awake. With this function any number of extra events can be used to\nawake the current thread (remember that ev actually is an event ring).\n\nint pthconnectev(int s, const struct sockaddr *addr, socklent addrlen, ptheventt ev);\nThis is equal to pthconnect(3) (see below), but has an additional event argument ev.\nWhen pthconnect(3) suspends the current threads execution it usually only uses the I/O\nevent on s to awake. With this function any number of extra events can be used to awake\nthe current thread (remember that ev actually is an event ring).\n\nint pthacceptev(int s, struct sockaddr *addr, socklent *addrlen, ptheventt ev);\nThis is equal to pthaccept(3) (see below), but has an additional event argument ev. When\npthaccept(3) suspends the current threads execution it usually only uses the I/O event\non s to awake. With this function any number of extra events can be used to awake the\ncurrent thread (remember that ev actually is an event ring).\n\nint pthselectev(int nfd, fdset *rfds, fdset *wfds, fdset *efds, struct timeval *timeout,\nptheventt ev);\nThis is equal to pthselect(3) (see below), but has an additional event argument ev. When\npthselect(3) suspends the current threads execution it usually only uses the I/O event\non rfds, wfds and efds to awake. With this function any number of extra events can be\nused to awake the current thread (remember that ev actually is an event ring).\n\nint pthpollev(struct pollfd *fds, unsigned int nfd, int timeout, ptheventt ev);\nThis is equal to pthpoll(3) (see below), but has an additional event argument ev. When\npthpoll(3) suspends the current threads execution it usually only uses the I/O event on\nfds to awake. With this function any number of extra events can be used to awake the cur‐\nrent thread (remember that ev actually is an event ring).\n\nssizet pthreadev(int fd, void *buf, sizet nbytes, ptheventt ev);\nThis is equal to pthread(3) (see below), but has an additional event argument ev. When\npthread(3) suspends the current threads execution it usually only uses the I/O event on\nfd to awake. With this function any number of extra events can be used to awake the cur‐\nrent thread (remember that ev actually is an event ring).\n\nssizet pthreadvev(int fd, const struct iovec *iovec, int iovcnt, ptheventt ev);\nThis is equal to pthreadv(3) (see below), but has an additional event argument ev. When\npthreadv(3) suspends the current threads execution it usually only uses the I/O event on\nfd to awake. With this function any number of extra events can be used to awake the cur‐\nrent thread (remember that ev actually is an event ring).\n\nssizet pthwriteev(int fd, const void *buf, sizet nbytes, ptheventt ev);\nThis is equal to pthwrite(3) (see below), but has an additional event argument ev. When\npthwrite(3) suspends the current threads execution it usually only uses the I/O event on\nfd to awake. With this function any number of extra events can be used to awake the cur‐\nrent thread (remember that ev actually is an event ring).\n\nssizet pthwritevev(int fd, const struct iovec *iovec, int iovcnt, ptheventt ev);\nThis is equal to pthwritev(3) (see below), but has an additional event argument ev. When\npthwritev(3) suspends the current threads execution it usually only uses the I/O event\non fd to awake. With this function any number of extra events can be used to awake the\ncurrent thread (remember that ev actually is an event ring).\n\nssizet pthrecvev(int fd, void *buf, sizet nbytes, int flags, ptheventt ev);\nThis is equal to pthrecv(3) (see below), but has an additional event argument ev. When\npthrecv(3) suspends the current threads execution it usually only uses the I/O event on\nfd to awake. With this function any number of extra events can be used to awake the cur‐\nrent thread (remember that ev actually is an event ring).\n\nssizet pthrecvfromev(int fd, void *buf, sizet nbytes, int flags, struct sockaddr *from,\nsocklent *fromlen, ptheventt ev);\nThis is equal to pthrecvfrom(3) (see below), but has an additional event argument ev.\nWhen pthrecvfrom(3) suspends the current threads execution it usually only uses the I/O\nevent on fd to awake. With this function any number of extra events can be used to awake\nthe current thread (remember that ev actually is an event ring).\n\nssizet pthsendev(int fd, const void *buf, sizet nbytes, int flags, ptheventt ev);\nThis is equal to pthsend(3) (see below), but has an additional event argument ev. When\npthsend(3) suspends the current threads execution it usually only uses the I/O event on\nfd to awake. With this function any number of extra events can be used to awake the cur‐\nrent thread (remember that ev actually is an event ring).\n\nssizet pthsendtoev(int fd, const void *buf, sizet nbytes, int flags, const struct sock‐\naddr *to, socklent tolen, ptheventt ev);\nThis is equal to pthsendto(3) (see below), but has an additional event argument ev. When\npthsendto(3) suspends the current threads execution it usually only uses the I/O event\non fd to awake. With this function any number of extra events can be used to awake the\ncurrent thread (remember that ev actually is an event ring).\n"
                },
                {
                    "name": "Standard POSIX Replacement API",
                    "content": "The following functions are standard replacements functions for the POSIX API.  The differ‐\nence is mainly that they suspend the current thread only instead of the whole process in case\nthe file descriptors will block.\n\nint pthnanosleep(const struct timespec *rqtp, struct timespec *rmtp);\nThis is a variant of the POSIX nanosleep(3) function. It suspends the current threads ex‐\necution until the amount of time in rqtp elapsed.  The thread is guaranteed to not wake\nup before this time, but because of the non-preemptive scheduling nature of Pth, it can\nbe awakened later, of course. If rmtp is not \"NULL\", the \"timespec\" structure it refer‐\nences is updated to contain the unslept amount (the request time minus the time actually\nslept time). The difference between nanosleep(3) and pthnanosleep(3) is that that\npthnanosleep(3) suspends only the execution of the current thread and not the whole\nprocess.\n\nint pthusleep(unsigned int usec);\nThis is a variant of the 4.3BSD usleep(3) function. It suspends the current threads exe‐\ncution until usec microseconds (= usec*1/1000000 sec) elapsed.  The thread is guaranteed\nto not wake up before this time, but because of the non-preemptive scheduling nature of\nPth, it can be awakened later, of course.  The difference between usleep(3) and\npthusleep(3) is that that pthusleep(3) suspends only the execution of the current\nthread and not the whole process.\n\nunsigned int pthsleep(unsigned int sec);\nThis is a variant of the POSIX sleep(3) function. It suspends the current threads execu‐\ntion until sec seconds elapsed.  The thread is guaranteed to not wake up before this\ntime, but because of the non-preemptive scheduling nature of Pth, it can be awakened\nlater, of course.  The difference between sleep(3) and pthsleep(3) is that pthsleep(3)\nsuspends only the execution of the current thread and not the whole process.\n\npidt pthwaitpid(pidt pid, int *status, int options);\nThis is a variant of the POSIX waitpid(2) function. It suspends the current threads exe‐\ncution until status information is available for a terminated child process pid.  The\ndifference between waitpid(2) and pthwaitpid(3) is that pthwaitpid(3) suspends only the\nexecution of the current thread and not the whole process.  For more details about the\narguments and return code semantics see waitpid(2).\n\nint pthsystem(const char *cmd);\nThis is a variant of the POSIX system(3) function. It executes the shell command cmd with\nBourne Shell (\"sh\") and suspends the current threads execution until this command termi‐\nnates. The difference between system(3) and pthsystem(3) is that pthsystem(3) suspends\nonly the execution of the current thread and not the whole process. For more details\nabout the arguments and return code semantics see system(3).\n\nint pthsigmask(int how, const sigsett *set, sigsett *oset)\nThis is the Pth thread-related equivalent of POSIX sigprocmask(2) respectively\npthreadsigmask(3). The arguments how, set and oset directly relate to sigprocmask(2),\nbecause Pth internally just uses sigprocmask(2) here. So alternatively you can also di‐\nrectly call sigprocmask(2), but for consistency reasons you should use this function\npthsigmask(3).\n\nint pthsigwait(const sigsett *set, int *sig);\nThis is a variant of the POSIX.1c sigwait(3) function. It suspends the current threads\nexecution until a signal in set occurred and stores the signal number in sig. The impor‐\ntant point is that the signal is not delivered to a signal handler. Instead it's caught\nby the scheduler only in order to awake the pthsigwait() call. The trick and noticeable\npoint here is that this way you get an asynchronous aware application that is written\ncompletely synchronously. When you think about the problem of asynchronous safe functions\nyou should recognize that this is a great benefit.\n\nint pthconnect(int s, const struct sockaddr *addr, socklent addrlen);\nThis is a variant of the 4.2BSD connect(2) function. It establishes a connection on a\nsocket s to target specified in addr and addrlen.  The difference between connect(2) and\npthconnect(3) is that pthconnect(3) suspends only the execution of the current thread\nand not the whole process.  For more details about the arguments and return code seman‐\ntics see connect(2).\n\nint pthaccept(int s, struct sockaddr *addr, socklent *addrlen);\nThis is a variant of the 4.2BSD accept(2) function. It accepts a connection on a socket\nby extracting the first connection request on the queue of pending connections, creating\na new socket with the same properties of s and allocates a new file descriptor for the\nsocket (which is returned).  The difference between accept(2) and pthaccept(3) is that\npthaccept(3) suspends only the execution of the current thread and not the whole\nprocess.  For more details about the arguments and return code semantics see accept(2).\n\nint pthselect(int nfd, fdset *rfds, fdset *wfds, fdset *efds, struct timeval *timeout);\nThis is a variant of the 4.2BSD select(2) function.  It examines the I/O descriptor sets\nwhose addresses are passed in rfds, wfds, and efds to see if some of their descriptors\nare ready for reading, are ready for writing, or have an exceptional condition pending,\nrespectively.  For more details about the arguments and return code semantics see se‐\nlect(2).\n\nint pthpselect(int nfd, fdset *rfds, fdset *wfds, fdset *efds, const struct timespec\n*timeout, const sigsett *sigmask);\nThis is a variant of the POSIX pselect(2) function, which in turn is a stronger variant\nof 4.2BSD select(2). The difference is that the higher-resolution \"struct timespec\" is\npassed instead of the lower-resolution \"struct timeval\" and that a signal mask is speci‐\nfied which is temporarily set while waiting for input. For more details about the argu‐\nments and return code semantics see pselect(2) and select(2).\n\nint pthpoll(struct pollfd *fds, unsigned int nfd, int timeout);\nThis is a variant of the SysV poll(2) function. It examines the I/O descriptors which are\npassed in the array fds to see if some of them are ready for reading, are ready for writ‐\ning, or have an exceptional condition pending, respectively. For more details about the\narguments and return code semantics see poll(2).\n\nssizet pthread(int fd, void *buf, sizet nbytes);\nThis is a variant of the POSIX read(2) function. It reads up to nbytes bytes into buf\nfrom file descriptor fd.  The difference between read(2) and pthread(2) is that\npthread(2) suspends execution of the current thread until the file descriptor is ready\nfor reading. For more details about the arguments and return code semantics see read(2).\n\nssizet pthreadv(int fd, const struct iovec *iovec, int iovcnt);\nThis is a variant of the POSIX readv(2) function. It reads data from file descriptor fd\ninto the first iovcnt rows of the iov vector.  The difference between readv(2) and\npthreadv(2) is that pthreadv(2) suspends execution of the current thread until the file\ndescriptor is ready for reading. For more details about the arguments and return code se‐\nmantics see readv(2).\n\nssizet pthwrite(int fd, const void *buf, sizet nbytes);\nThis is a variant of the POSIX write(2) function. It writes nbytes bytes from buf to file\ndescriptor fd.  The difference between write(2) and pthwrite(2) is that pthwrite(2)\nsuspends execution of the current thread until the file descriptor is ready for writing.\nFor more details about the arguments and return code semantics see write(2).\n\nssizet pthwritev(int fd, const struct iovec *iovec, int iovcnt);\nThis is a variant of the POSIX writev(2) function. It writes data to file descriptor fd\nfrom the first iovcnt rows of the iov vector.  The difference between writev(2) and\npthwritev(2) is that pthwritev(2) suspends execution of the current thread until the\nfile descriptor is ready for reading. For more details about the arguments and return\ncode semantics see writev(2).\n\nssizet pthpread(int fd, void *buf, sizet nbytes, offt offset);\nThis is a variant of the POSIX pread(3) function.  It performs the same action as a regu‐\nlar read(2), except that it reads from a given position in the file without changing the\nfile pointer.  The first three arguments are the same as for pthread(3) with the addi‐\ntion of a fourth argument offset for the desired position inside the file.\n\nssizet pthpwrite(int fd, const void *buf, sizet nbytes, offt offset);\nThis is a variant of the POSIX pwrite(3) function.  It performs the same action as a reg‐\nular write(2), except that it writes to a given position in the file without changing the\nfile pointer. The first three arguments are the same as for pthwrite(3) with the addi‐\ntion of a fourth argument offset for the desired position inside the file.\n\nssizet pthrecv(int fd, void *buf, sizet nbytes, int flags);\nThis is a variant of the SUSv2 recv(2) function and equal to ``pthrecvfrom(fd, buf,\nnbytes, flags, NULL, 0)''.\n\nssizet pthrecvfrom(int fd, void *buf, sizet nbytes, int flags, struct sockaddr *from,\nsocklent *fromlen);\nThis is a variant of the SUSv2 recvfrom(2) function. It reads up to nbytes bytes into buf\nfrom file descriptor fd while using flags and from/fromlen. The difference between\nrecvfrom(2) and pthrecvfrom(2) is that pthrecvfrom(2) suspends execution of the current\nthread until the file descriptor is ready for reading. For more details about the argu‐\nments and return code semantics see recvfrom(2).\n\nssizet pthsend(int fd, const void *buf, sizet nbytes, int flags);\nThis is a variant of the SUSv2 send(2) function and equal to ``pthsendto(fd, buf,\nnbytes, flags, NULL, 0)''.\n\nssizet pthsendto(int fd, const void *buf, sizet nbytes, int flags, const struct sockaddr\n*to, socklent tolen);\nThis is a variant of the SUSv2 sendto(2) function. It writes nbytes bytes from buf to\nfile descriptor fd while using flags and to/tolen. The difference between sendto(2) and\npthsendto(2) is that pthsendto(2) suspends execution of the current thread until the\nfile descriptor is ready for writing. For more details about the arguments and return\ncode semantics see sendto(2).\n"
                }
            ]
        },
        "EXAMPLE": {
            "content": "The following example is a useless server which does nothing more than listening on TCP port\n12345 and displaying the current time to the socket when a connection was established. For\neach incoming connection a thread is spawned. Additionally, to see more multithreading, a\nuseless ticker thread runs simultaneously which outputs the current time to \"stderr\" every 5\nseconds. The example contains no error checking and is only intended to show you the look and\nfeel of Pth.\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <signal.h>\n#include <netdb.h>\n#include <unistd.h>\n#include \"pth.h\"\n\n#define PORT 12345\n\n/* the socket connection handler thread */\nstatic void *handler(void *arg)\n{\nint fd = (int)arg;\ntimet now;\nchar *ct;\n\nnow = time(NULL);\nct = ctime(&now);\npthwrite(fd, ct, strlen(ct));\nclose(fd);\nreturn NULL;\n}\n\n/* the stderr time ticker thread */\nstatic void *ticker(void *arg)\n{\ntimet now;\nchar *ct;\nfloat load;\n\nfor (;;) {\npthsleep(5);\nnow = time(NULL);\nct = ctime(&now);\nct[strlen(ct)-1] = '\\0';\npthctrl(PTHCTRLGETAVLOAD, &load);\nprintf(\"ticker: time: %s, average load: %.2f\\n\", ct, load);\n}\n}\n\n/* the main thread/procedure */\nint main(int argc, char *argv[])\n{\npthattrt attr;\nstruct sockaddrin sar;\nstruct protoent *pe;\nstruct sockaddrin peeraddr;\nint peerlen;\nint sa, sw;\nint port;\n\npthinit();\nsignal(SIGPIPE, SIGIGN);\n\nattr = pthattrnew();\npthattrset(attr, PTHATTRNAME, \"ticker\");\npthattrset(attr, PTHATTRSTACKSIZE, 64*1024);\npthattrset(attr, PTHATTRJOINABLE, FALSE);\npthspawn(attr, ticker, NULL);\n\npe = getprotobyname(\"tcp\");\nsa = socket(AFINET, SOCKSTREAM, pe->pproto);\nsar.sinfamily = AFINET;\nsar.sinaddr.saddr = INADDRANY;\nsar.sinport = htons(PORT);\nbind(sa, (struct sockaddr *)&sar, sizeof(struct sockaddrin));\nlisten(sa, 10);\n\npthattrset(attr, PTHATTRNAME, \"handler\");\nfor (;;) {\npeerlen = sizeof(peeraddr);\nsw = pthaccept(sa, (struct sockaddr *)&peeraddr, &peerlen);\npthspawn(attr, handler, (void *)sw);\n}\n}\n",
            "subsections": []
        },
        "BUILD ENVIRONMENTS": {
            "content": "In this section we will discuss the canonical ways to establish the build environment for a\nPth based program. The possibilities supported by Pth range from very simple environments to\nrather complex ones.\n",
            "subsections": [
                {
                    "name": "Manual Build Environment (Novice)",
                    "content": "As a first example, assume we have the above test program staying in the source file \"foo.c\".\nThen we can create a very simple build environment by just adding the following \"Makefile\":\n\n$ vi Makefile\n⎪ CC      = cc\n⎪ CFLAGS  = `pth-config --cflags`\n⎪ LDFLAGS = `pth-config --ldflags`\n⎪ LIBS    = `pth-config --libs`\n⎪\n⎪ all: foo\n⎪ foo: foo.o\n⎪     $(CC) $(LDFLAGS) -o foo foo.o $(LIBS)\n⎪ foo.o: foo.c\n⎪     $(CC) $(CFLAGS) -c foo.c\n⎪ clean:\n⎪     rm -f foo foo.o\n\nThis imports the necessary compiler and linker flags on-the-fly from the Pth installation via\nits \"pth-config\" program. This approach is straight-forward and works fine for small\nprojects.\n"
                },
                {
                    "name": "Autoconf Build Environment (Advanced)",
                    "content": "The previous approach is simple but inflexible. First, to speed up building, it would be nice\nto not expand the compiler and linker flags every time the compiler is started. Second, it\nwould be useful to also be able to build against uninstalled Pth, that is, against a Pth\nsource tree which was just configured and built, but not installed. Third, it would be also\nuseful to allow checking of the Pth version to make sure it is at least a minimum required\nversion.  And finally, it would be also great to make sure Pth works correctly by first per‐\nforming some sanity compile and run-time checks. All this can be done if we use GNU autoconf\nand the \"ACCHECKPTH\" macro provided by Pth. For this, we establish the following three\nfiles:\n\nFirst we again need the \"Makefile\", but this time it contains autoconf placeholders and addi‐\ntional cleanup targets. And we create it under the name \"Makefile.in\", because it is now an\ninput file for autoconf:\n\n$ vi Makefile.in\n⎪ CC      = @CC@\n⎪ CFLAGS  = @CFLAGS@\n⎪ LDFLAGS = @LDFLAGS@\n⎪ LIBS    = @LIBS@\n⎪\n⎪ all: foo\n⎪ foo: foo.o\n⎪     $(CC) $(LDFLAGS) -o foo foo.o $(LIBS)\n⎪ foo.o: foo.c\n⎪     $(CC) $(CFLAGS) -c foo.c\n⎪ clean:\n⎪     rm -f foo foo.o\n⎪ distclean:\n⎪     rm -f foo foo.o\n⎪     rm -f config.log config.status config.cache\n⎪     rm -f Makefile\n\nBecause autoconf generates additional files, we added a canonical \"distclean\" target which\ncleans this up. Secondly, we wrote \"configure.ac\", a (minimal) autoconf script specification:\n\n$ vi configure.ac\n⎪ ACINIT(Makefile.in)\n⎪ ACCHECKPTH(1.3.0)\n⎪ ACOUTPUT(Makefile)\n\nThen we let autoconf's \"aclocal\" program generate for us an \"aclocal.m4\" file containing\nPth's \"ACCHECKPTH\" macro. Then we generate the final \"configure\" script out of this \"aclo‐\ncal.m4\" file and the \"configure.ac\" file:\n\n$ aclocal --acdir=`pth-config --acdir`\n$ autoconf\n\nAfter these steps, the working directory should look similar to this:\n\n$ ls -l\n-rw-r--r--  1 rse  users    176 Nov  3 11:11 Makefile.in\n-rw-r--r--  1 rse  users  15314 Nov  3 11:16 aclocal.m4\n-rwxr-xr-x  1 rse  users  52045 Nov  3 11:16 configure\n-rw-r--r--  1 rse  users     63 Nov  3 11:11 configure.ac\n-rw-r--r--  1 rse  users   4227 Nov  3 11:11 foo.c\n\nIf we now run \"configure\" we get a correct \"Makefile\" which immediately can be used to build\n\"foo\" (assuming that Pth is already installed somewhere, so that \"pth-config\" is in $PATH):\n\n$ ./configure\ncreating cache ./config.cache\nchecking for gcc... gcc\nchecking whether the C compiler (gcc   ) works... yes\nchecking whether the C compiler (gcc   ) is a cross-compiler... no\nchecking whether we are using GNU C... yes\nchecking whether gcc accepts -g... yes\nchecking how to run the C preprocessor... gcc -E\nchecking for GNU Pth... version 1.3.0, installed under /usr/local\nupdating cache ./config.cache\ncreating ./config.status\ncreating Makefile\nrse@en1:/e/gnu/pth/ac\n$ make\ngcc -g -O2 -I/usr/local/include -c foo.c\ngcc -L/usr/local/lib -o foo foo.o -lpth\n\nIf Pth is installed in non-standard locations or \"pth-config\" is not in $PATH, one just has\nto drop the \"configure\" script a note about the location by running \"configure\" with the op‐\ntion \"--with-pth=\"dir (where dir is the argument which was used with the \"--prefix\" option\nwhen Pth was installed).\n"
                },
                {
                    "name": "Autoconf Build Environment with Local Copy of Pth (Expert)",
                    "content": "Finally let us assume the \"foo\" program stays under either a GPL or LGPL distribution license\nand we want to make it a stand-alone package for easier distribution and installation.  That\nis, we don't want to oblige the end-user to install Pth just to allow our \"foo\" package to\ncompile. For this, it is a convenient practice to include the required libraries (here Pth)\ninto the source tree of the package (here \"foo\").  Pth ships with all necessary support to\nallow us to easily achieve this approach. Say, we want Pth in a subdirectory named \"pth/\" and\nthis directory should be seamlessly integrated into the configuration and build process of\n\"foo\".\n\nFirst we again start with the \"Makefile.in\", but this time it is a more advanced version\nwhich supports subdirectory movement:\n\n$ vi Makefile.in\n⎪ CC      = @CC@\n⎪ CFLAGS  = @CFLAGS@\n⎪ LDFLAGS = @LDFLAGS@\n⎪ LIBS    = @LIBS@\n⎪\n⎪ SUBDIRS = pth\n⎪\n⎪ all: subdirsall foo\n⎪\n⎪ subdirsall:\n⎪     @$(MAKE) $(MFLAGS) subdirs TARGET=all\n⎪ subdirsclean:\n⎪     @$(MAKE) $(MFLAGS) subdirs TARGET=clean\n⎪ subdirsdistclean:\n⎪     @$(MAKE) $(MFLAGS) subdirs TARGET=distclean\n⎪ subdirs:\n⎪     @for subdir in $(SUBDIRS); do \\\n⎪         echo \"===> $$subdir ($(TARGET))\"; \\\n⎪         (cd $$subdir; $(MAKE) $(MFLAGS) $(TARGET) ⎪⎪ exit 1) ⎪⎪ exit 1; \\\n⎪         echo \"<=== $$subdir\"; \\\n⎪     done\n⎪\n⎪ foo: foo.o\n⎪     $(CC) $(LDFLAGS) -o foo foo.o $(LIBS)\n⎪ foo.o: foo.c\n⎪     $(CC) $(CFLAGS) -c foo.c\n⎪\n⎪ clean: subdirsclean\n⎪     rm -f foo foo.o\n⎪ distclean: subdirsdistclean\n⎪     rm -f foo foo.o\n⎪     rm -f config.log config.status config.cache\n⎪     rm -f Makefile\n\nThen we create a slightly different autoconf script \"configure.ac\":\n\n$ vi configure.ac\n⎪ ACINIT(Makefile.in)\n⎪ ACCONFIGAUXDIR(pth)\n⎪ ACCHECKPTH(1.3.0, subdir:pth --disable-tests)\n⎪ ACCONFIGSUBDIRS(pth)\n⎪ ACOUTPUT(Makefile)\n\nHere we provided a default value for \"foo\"'s \"--with-pth\" option as the second argument to\n\"ACCHECKPTH\" which indicates that Pth can be found in the subdirectory named \"pth/\". Addi‐\ntionally we specified that the \"--disable-tests\" option of Pth should be passed to the \"pth/\"\nsubdirectory, because we need only to build the Pth library itself. And we added a \"ACCON‐\nFIGSUBDIR\" call which indicates to autoconf that it should configure the \"pth/\" subdirec‐\ntory, too. The \"ACCONFIGAUXDIR\" directive was added just to make autoconf happy, because\nit wants to find a \"install.sh\" or \"shtool\" script if \"ACCONFIGSUBDIRS\" is used.\n\nNow we let autoconf's \"aclocal\" program again generate for us an \"aclocal.m4\" file with the\ncontents of Pth's \"ACCHECKPTH\" macro.  Finally we generate the \"configure\" script out of\nthis \"aclocal.m4\" file and the \"configure.ac\" file.\n\n$ aclocal --acdir=`pth-config --acdir`\n$ autoconf\n\nNow we have to create the \"pth/\" subdirectory itself. For this, we extract the Pth distribu‐\ntion to the \"foo\" source tree and just rename it to \"pth/\":\n\n$ gunzip <pth-X.Y.Z.tar.gz ⎪ tar xvf -\n$ mv pth-X.Y.Z pth\n\nOptionally to reduce the size of the \"pth/\" subdirectory, we can strip down the Pth sources\nto a minimum with the striptease feature:\n\n$ cd pth\n$ ./configure\n$ make striptease\n$ cd ..\n\nAfter this the source tree of \"foo\" should look similar to this:\n\n$ ls -l\n-rw-r--r--  1 rse  users    709 Nov  3 11:51 Makefile.in\n-rw-r--r--  1 rse  users  16431 Nov  3 12:20 aclocal.m4\n-rwxr-xr-x  1 rse  users  57403 Nov  3 12:21 configure\n-rw-r--r--  1 rse  users    129 Nov  3 12:21 configure.ac\n-rw-r--r--  1 rse  users   4227 Nov  3 11:11 foo.c\ndrwxr-xr-x  2 rse  users   3584 Nov  3 12:36 pth\n$ ls -l pth/\n-rw-rw-r--  1 rse  users   26344 Nov  1 20:12 COPYING\n-rw-rw-r--  1 rse  users    2042 Nov  3 12:36 Makefile.in\n-rw-rw-r--  1 rse  users    3967 Nov  1 19:48 README\n-rw-rw-r--  1 rse  users     340 Nov  3 12:36 README.1st\n-rw-rw-r--  1 rse  users   28719 Oct 31 17:06 config.guess\n-rw-rw-r--  1 rse  users   24274 Aug 18 13:31 config.sub\n-rwxrwxr-x  1 rse  users  155141 Nov  3 12:36 configure\n-rw-rw-r--  1 rse  users  162021 Nov  3 12:36 pth.c\n-rw-rw-r--  1 rse  users   18687 Nov  2 15:19 pth.h.in\n-rw-rw-r--  1 rse  users    5251 Oct 31 12:46 pthacdef.h.in\n-rw-rw-r--  1 rse  users    2120 Nov  1 11:27 pthacmac.h.in\n-rw-rw-r--  1 rse  users    2323 Nov  1 11:27 pthp.h.in\n-rw-rw-r--  1 rse  users     946 Nov  1 11:27 pthvers.c\n-rw-rw-r--  1 rse  users   26848 Nov  1 11:27 pthread.c\n-rw-rw-r--  1 rse  users   18772 Nov  1 11:27 pthread.h.in\n-rwxrwxr-x  1 rse  users   26188 Nov  3 12:36 shtool\n\nNow when we configure and build the \"foo\" package it looks similar to this:\n\n$ ./configure\ncreating cache ./config.cache\nchecking for gcc... gcc\nchecking whether the C compiler (gcc   ) works... yes\nchecking whether the C compiler (gcc   ) is a cross-compiler... no\nchecking whether we are using GNU C... yes\nchecking whether gcc accepts -g... yes\nchecking how to run the C preprocessor... gcc -E\nchecking for GNU Pth... version 1.3.0, local under pth\nupdating cache ./config.cache\ncreating ./config.status\ncreating Makefile\nconfiguring in pth\nrunning /bin/sh ./configure  --enable-subdir --enable-batch\n--disable-tests --cache-file=.././config.cache --srcdir=.\nloading cache .././config.cache\nchecking for gcc... (cached) gcc\nchecking whether the C compiler (gcc   ) works... yes\nchecking whether the C compiler (gcc   ) is a cross-compiler... no\n[...]\n$ make\n===> pth (all)\n./shtool scpp -o pthp.h -t pthp.h.in -Dcpp -Cintern -M '==#==' pth.c\npthvers.c\ngcc -c -I. -O2 -pipe pth.c\ngcc -c -I. -O2 -pipe pthvers.c\nar rc libpth.a pth.o pthvers.o\nranlib libpth.a\n<=== pth\ngcc -g -O2 -Ipth -c foo.c\ngcc -Lpth -o foo foo.o -lpth\n\nAs you can see, autoconf now automatically configures the local (stripped down) copy of Pth\nin the subdirectory \"pth/\" and the \"Makefile\" automatically builds the subdirectory, too.\n"
                }
            ]
        },
        "SYSTEM CALL WRAPPER FACILITY": {
            "content": "Pth per default uses an explicit API, including the system calls. For instance you've to ex‐\nplicitly use pthread(3) when you need a thread-aware read(3) and cannot expect that by just\ncalling read(3) only the current thread is blocked. Instead with the standard read(3) call\nthe whole process will be blocked. But because for some applications (mainly those consisting\nof lots of third-party stuff) this can be inconvenient.  Here it's required that a call to\nread(3) `magically' means pthread(3). The problem here is that such magic Pth cannot provide\nper default because it's not really portable.  Nevertheless Pth provides a two step approach\nto solve this problem:\n",
            "subsections": [
                {
                    "name": "Soft System Call Mapping",
                    "content": "This variant is available on all platforms and can always be enabled by building Pth with\n\"--enable-syscall-soft\". This then triggers some \"#define\"'s in the \"pth.h\" header which map\nfor instance read(3) to pthread(3), etc. Currently the following functions are mapped:\nfork(2), nanosleep(3), usleep(3), sleep(3), sigwait(3), waitpid(2), system(3), select(2),\npoll(2), connect(2), accept(2), read(2), write(2), recv(2), send(2), recvfrom(2), sendto(2).\n\nThe drawback of this approach is just that really all source files of the application where\nthese function calls occur have to include \"pth.h\", of course. And this also means that ex‐\nisting libraries, including the vendor's stdio, usually will still block the whole process if\none of its I/O functions block.\n"
                },
                {
                    "name": "Hard System Call Mapping",
                    "content": "This variant is available only on those platforms where the syscall(2) function exists and\nthere it can be enabled by building Pth with \"--enable-syscall-hard\". This then builds wrap‐\nper functions (for instances read(3)) into the Pth library which internally call the real Pth\nreplacement functions (pthread(3)). Currently the following functions are mapped: fork(2),\nnanosleep(3), usleep(3), sleep(3), waitpid(2), system(3), select(2), poll(2), connect(2), ac‐\ncept(2), read(2), write(2).\n\nThe drawback of this approach is that it depends on syscall(2) interface and prototype con‐\nflicts can occur while building the wrapper functions due to different function signatures in\nthe vendor C header files.  But the advantage of this mapping variant is that the source\nfiles of the application where these function calls occur have not to include \"pth.h\" and\nthat existing libraries, including the vendor's stdio, magically become thread-aware (and\nthen block only the current thread).\n"
                }
            ]
        },
        "IMPLEMENTATION NOTES": {
            "content": "Pth is very portable because it has only one part which perhaps has to be ported to new plat‐\nforms (the machine context initialization). But it is written in a way which works on mostly\nall Unix platforms which support makecontext(2) or at least sigstack(2) or sigaltstack(2)\n[see \"pthmctx.c\" for details]. Any other Pth code is POSIX and ANSI C based only.\n\nThe context switching is done via either SUSv2 makecontext(2) or POSIX make[sig]setjmp(3) and\n[sig]longjmp(3). Here all CPU registers, the program counter and the stack pointer are\nswitched. Additionally the Pth dispatcher switches also the global Unix \"errno\" variable [see\n\"pthmctx.c\" for details] and the signal mask (either implicitly via sigsetjmp(3) or in an\nemulated way via explicit setprocmask(2) calls).\n\nThe Pth event manager is mainly select(2) and gettimeofday(2) based, i.e., the current time\nis fetched via gettimeofday(2) once per context switch for time calculations and all I/O\nevents are implemented via a single central select(2) call [see \"pthsched.c\" for details].\n\nThe thread control block management is done via virtual priority queues without any addi‐\ntional data structure overhead. For this, the queue linkage attributes are part of the thread\ncontrol blocks and the queues are actually implemented as rings with a selected element as\nthe entry point [see \"pthtcb.h\" and \"pthpqueue.c\" for details].\n\nMost time critical code sections (especially the dispatcher and event manager) are speeded up\nby inline functions (implemented as ANSI C pre-processor macros). Additionally any debugging\ncode is completely removed from the source when not built with \"-DPTHDEBUG\" (see Autoconf\n\"--enable-debug\" option), i.e., not only stub functions remain [see \"pthdebug.c\" for de‐\ntails].\n",
            "subsections": []
        },
        "RESTRICTIONS": {
            "content": "",
            "subsections": [
                {
                    "name": "Pth (intentionally)",
                    "content": "which uses a static internal buffer) or synchronous system functions (like gethostbyname(3)\nwhich doesn't provide an asynchronous mode where it doesn't block). When you want to use\nthose functions in your server application together with threads, you've to either link the\napplication against special third-party libraries (or for thread-safe/reentrant functions\npossibly against an existing \"libcr\" of the platform vendor). For an asynchronous DNS re‐\nsolver library use the GNU adns package from Ian Jackson ( see http://www.gnu.org/soft‐\nware/adns/adns.html ).\n"
                }
            ]
        },
        "HISTORY": {
            "content": "The Pth library was designed and implemented between February and July 1999 by Ralf S. En‐\ngelschall after evaluating numerous (mostly preemptive) thread libraries and after intensive\ndiscussions with Peter Simons, Martin Kraemer, Lars Eilebrecht and Ralph Babel related to an\nexperimental (matrix based) non-preemptive C++ scheduler class written by Peter Simons.\n\nPth was then implemented in order to combine the non-preemptive approach of multithreading\n(which provides better portability and performance) with an API similar to the popular one\nfound in Pthread libraries (which provides easy programming).\n\nSo the essential idea of the non-preemptive approach was taken over from Peter Simons sched‐\nuler. The priority based scheduling algorithm was suggested by Martin Kraemer. Some code in‐\nspiration also came from an experimental threading library (rsthreads) written by Robert S.\nThau for an ancient internal test version of the Apache webserver.  The concept and API of\nmessage ports was borrowed from AmigaOS' Exec subsystem. The concept and idea for the flexi‐\nble event mechanism came from Paul Vixie's eventlib (which can be found as a part of BIND\nv8).\n",
            "subsections": []
        },
        "BUG REPORTS AND SUPPORT": {
            "content": "If you think you have found a bug in Pth, you should send a report as complete as possible to\nbug-pth@gnu.org. If you can, please try to fix the problem and include a patch, made with\n'\"diff -u3\"', in your report. Always, at least, include a reasonable amount of description in\nyour report to allow the author to deterministically reproduce the bug.\n\nFor further support you additionally can subscribe to the pth-users@gnu.org mailing list by\nsending an Email to pth-users-request@gnu.org with `\"subscribe pth-users\"' (or `\"subscribe\npth-users\" address' if you want to subscribe from a particular Email address) in the body.\nThen you can discuss your issues with other Pth users by sending messages to\npth-users@gnu.org. Currently (as of August 2000) you can reach about 110 Pth users on this\nmailing list. Old postings you can find at http://www.mail-archive.com/pth-users@gnu.org/.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "",
            "subsections": [
                {
                    "name": "Related Web Locations",
                    "content": "`comp.programming.threads Newsgroup Archive', http://www.deja.com/topicsif.xp?\nsearch=topic&group=comp.programming.threads\n\n`comp.programming.threads Frequently Asked Questions (F.A.Q.)', http://www.lambdacs.com/news‐\ngroup/FAQ.html\n\n`Multithreading - Definitions and Guidelines', Numeric Quest Inc 1998; http://www.nu‐\nmeric-quest.com/lang/multi-frame.html\n\n`The Single UNIX Specification, Version 2 - Threads', The Open Group 1997; http://www.open‐\ngroup.org/onlinepubs /007908799/xsh/threads.html\n\nSMI Thread Resources, Sun Microsystems Inc; http://www.sun.com/workshop/threads/\n\nBibliography on threads and multithreading, Torsten Amundsen; http://liinwww.ira.uka.de/bib‐\nliography/Os/threads.html\n"
                },
                {
                    "name": "Related Books",
                    "content": "B. Nichols, D. Buttlar, J.P. Farrel: `Pthreads Programming - A POSIX Standard for Better Mul‐\ntiprocessing', O'Reilly 1996; ISBN 1-56592-115-1\n\nB. Lewis, D. J. Berg: `Multithreaded Programming with Pthreads', Sun Microsystems Press,\nPrentice Hall 1998; ISBN 0-13-680729-1\n\nB. Lewis, D. J. Berg: `Threads Primer - A Guide To Multithreaded Programming', Prentice Hall\n1996; ISBN 0-13-443698-9\n\nS. J. Norton, M. D. Dipasquale: `Thread Time - The Multithreaded Programming Guide', Prentice\nHall 1997; ISBN 0-13-190067-6\n\nD. R. Butenhof: `Programming with POSIX Threads', Addison Wesley 1997; ISBN 0-201-63392-2\n"
                },
                {
                    "name": "Related Manpages",
                    "content": "pth-config(1), pthread(3).\n\ngetcontext(2), setcontext(2), makecontext(2), swapcontext(2), sigstack(2), sigaltstack(2),\nsigaction(2), sigemptyset(2), sigaddset(2), sigprocmask(2), sigsuspend(2), sigsetjmp(3), sig‐\nlongjmp(3), setjmp(3), longjmp(3), select(2), gettimeofday(2).\n"
                }
            ]
        },
        "AUTHOR": {
            "content": "Ralf S. Engelschall\nrse@engelschall.com\nwww.engelschall.com\n\n\n\n08-Jun-2006                                 GNU Pth 2.0.7                                     pth(3)",
            "subsections": []
        }
    },
    "summary": "pth - GNU Portable Threads",
    "flags": [],
    "examples": [
        "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;",
        "timet now;",
        "char *ct;",
        "now = time(NULL);",
        "ct = ctime(&now);",
        "pthwrite(fd, ct, strlen(ct));",
        "close(fd);",
        "return NULL;",
        "/* the stderr time ticker thread */",
        "static void *ticker(void *arg)",
        "timet now;",
        "char *ct;",
        "float load;",
        "for (;;) {",
        "pthsleep(5);",
        "now = time(NULL);",
        "ct = ctime(&now);",
        "ct[strlen(ct)-1] = '\\0';",
        "pthctrl(PTHCTRLGETAVLOAD, &load);",
        "printf(\"ticker: time: %s, average load: %.2f\\n\", ct, load);",
        "/* the main thread/procedure */",
        "int main(int argc, char *argv[])",
        "pthattrt attr;",
        "struct sockaddrin sar;",
        "struct protoent *pe;",
        "struct sockaddrin peeraddr;",
        "int peerlen;",
        "int sa, sw;",
        "int port;",
        "pthinit();",
        "signal(SIGPIPE, SIGIGN);",
        "attr = pthattrnew();",
        "pthattrset(attr, PTHATTRNAME, \"ticker\");",
        "pthattrset(attr, PTHATTRSTACKSIZE, 64*1024);",
        "pthattrset(attr, PTHATTRJOINABLE, FALSE);",
        "pthspawn(attr, ticker, NULL);",
        "pe = getprotobyname(\"tcp\");",
        "sa = socket(AFINET, SOCKSTREAM, pe->pproto);",
        "sar.sinfamily = AFINET;",
        "sar.sinaddr.saddr = INADDRANY;",
        "sar.sinport = htons(PORT);",
        "bind(sa, (struct sockaddr *)&sar, sizeof(struct sockaddrin));",
        "listen(sa, 10);",
        "pthattrset(attr, PTHATTRNAME, \"handler\");",
        "for (;;) {",
        "peerlen = sizeof(peeraddr);",
        "sw = pthaccept(sa, (struct sockaddr *)&peeraddr, &peerlen);",
        "pthspawn(attr, handler, (void *)sw);"
    ],
    "see_also": [
        {
            "name": "pth-config",
            "section": "1",
            "url": "https://www.chedong.com/phpMan.php/man/pth-config/1/json"
        },
        {
            "name": "pthread",
            "section": "3",
            "url": "https://www.chedong.com/phpMan.php/man/pthread/3/json"
        },
        {
            "name": "getcontext",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/getcontext/2/json"
        },
        {
            "name": "setcontext",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/setcontext/2/json"
        },
        {
            "name": "makecontext",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/makecontext/2/json"
        },
        {
            "name": "swapcontext",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/swapcontext/2/json"
        },
        {
            "name": "sigstack",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/sigstack/2/json"
        },
        {
            "name": "sigaltstack",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/sigaltstack/2/json"
        },
        {
            "name": "sigaction",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/sigaction/2/json"
        },
        {
            "name": "sigemptyset",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/sigemptyset/2/json"
        },
        {
            "name": "sigaddset",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/sigaddset/2/json"
        },
        {
            "name": "sigprocmask",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/sigprocmask/2/json"
        },
        {
            "name": "sigsuspend",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/sigsuspend/2/json"
        },
        {
            "name": "sigsetjmp",
            "section": "3",
            "url": "https://www.chedong.com/phpMan.php/man/sigsetjmp/3/json"
        },
        {
            "name": "longjmp",
            "section": "3",
            "url": "https://www.chedong.com/phpMan.php/man/longjmp/3/json"
        },
        {
            "name": "setjmp",
            "section": "3",
            "url": "https://www.chedong.com/phpMan.php/man/setjmp/3/json"
        },
        {
            "name": "longjmp",
            "section": "3",
            "url": "https://www.chedong.com/phpMan.php/man/longjmp/3/json"
        },
        {
            "name": "select",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/select/2/json"
        },
        {
            "name": "gettimeofday",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/gettimeofday/2/json"
        }
    ]
}