文档介绍:Advanced Linux Programming M. Barbeau
Pthreads
Traditional Unix process
Child processes created from a parent process using mand fork.
Drawbacks:
• fork is expensive: Memory is copied from a parent to its children.
Logically a child process has a copy of the memory of the parent before
the fork (with copy-on-write semantics).
• Communication after the fork is expensive: Inter munication
is needed to pass information from parent to children and vice versa after
the fork has been done.
Threads
Lightweight processes:
• Creation 10 to 100 times faster than process creation
• Shared memory: all threads within a given process share the same
memory and files.
Pthreads: Posix threads standardised in 1995.
Creation and termination of threads
pthread_create()
#include <>
int pthread_create(
pthread_t * thread,
pthread_attr_t * attr,
void * (*start_routine)(void *),
void * arg);
pthread_create creates a new thread of control that executes
concurrently with the calling thread. The new thread applies the function
start_routine passing it arg as first argument. The new thread
1
Advanced Linux Programming M. Barbeau
terminates either explicitly, by calling pthread_exit(), or implicitly, by
returning from the start_routine function. The latter case is equivalent
to calling pthread_exit with the result returned by start_routine
as exit code.
The attr argument specifies thread attributes to be applied to the new
thread. The attr argument can be NULL, in which case default attributes
are used.
Each thread has an unique identifier, within a process, of date type
pthread_t. On ess, the identifier of the newly created thread is stored
in the location pointed by the thread argument, and a 0 is returned. On
error, a non-zero error code is returned.
pthread_join()
#include <>
int pthread_join(
pthread_t th,
void **thread_r