19-11-2012, 05:41 PM
Using the POSIX API
posix-api.pdf (Size: 956.57 KB / Downloads: 93)
The pthread library
In Linux, when a new process is created, it already contains a
thread, used to execute the main() function
Additional threads can be created using the pthread library, which
is part of the C library
Of course all threads inside a given process will share the same
address space, the same set of open files, etc.
The pthread library also provide thread synchronization
primitives: mutexes and conditions
This pthread library has its own header : pthread.h
Applications using pthread function calls should be explicitly
linked with the pthread library
gcc o
app app.c lpthread
Joinable and detached threads
When the main() function exits, all threads of the application are
destroyed
The pthread_join() function call can be used to suspend the
execution of a thread until another thread terminates. This
function must be called in order to release the ressources used
by the thread, otherwise it remains as zombie.
Threads can also be detached, in which case they become
independent. This can be achieved using
Thread attributes at thread creation, using
pthread_attr_setdetachstate(& attr,
PTHREAD_CREATE_DETACHED);
pthread_detach(), passing the pthread_t structure as
argument
pthread conditions
Conditions can be used to suspend a thread until a condition
becomes true, as signaled by another thread.
Initialization, static or dynamic
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond;
pthread_cond_init(& cond, NULL);
Wait for the condition
pthread_cond_wait(& cond, & mutex)
The mutex will be released before waiting and taken again after
the wait
Signaling the condition
To one thread waiting, pthread_cond_signal(& cond);
To all threads waiting, pthread_cond_broadcast(& cond);