Tiny Wiki : Fast loading, text only version of Wikipedia.

POSIX Threads

POSIX Threads, or Pthreads, is a POSIX standard for threads. The standard defines an API for creating and manipulating threads. Pthreads are most commonly used on Unix-like POSIX systems such as Linux and Solaris, but Microsoft Windows implementations also exist. For example, the pthreads-w32 is available and supports a subset of the Pthread API.

Contents



Pthreads defines a set of C programming language types, functions and constants. It is implemented with a [http://opengroup.org/onlinepubs/007908799/xsh/pthread.h.html pthread.h] header and a thread library. Programmers can use Pthreads to create, manipulate and manage threads, as well as synchronize between threads using mutexes and signals.

Example



An example of using Pthreads in C:


#include
#include
#include
#include

static void wait_thread(void)
{
time_t start_time = time(NULL);

while (time(NULL) == start_time)
{
// do nothing except chew CPU slices for up to one second.
}
}

static void *thread_func(void *vptr_args)
{
int i;

for (i = 0; i < 20; i++)
{
fputs(" b\n", stderr);
wait_thread();
}

return NULL;
}

int main(void)
{
int i;
pthread_t thread;

if (pthread_create(&thread, NULL, thread_func, NULL) != 0)
{
return EXIT_FAILURE;
}

for (i = 0; i < 20; i++)
{
fputs("a\n", stdout);
wait_thread();
}

if (pthread_join(thread, NULL) != 0)
{
return EXIT_FAILURE;
}

return EXIT_SUCCESS;
}


This program creates a new thread that prints lines containing 'b', while the main thread prints lines containing 'a'. The output is interleaved between 'a' and 'b' as a result of execution switching between the two threads.


Source: Wikipedia