- Pthreads refers to the POSIX standard (IEEE 1003.1c) defining an API for thread creation and synchronization.
- This is a specification for thread behavior, not an implementation. Operating system designers may implement the specification in any way they wish.
- Numerous systems implement the Pthreads specification, including Solaris, Linux, Mac OS X, and Tru64 UNIX. Shareware implementations are available in the public domain for the various Windows OSs as well.
Figure 8:
Some of the Pthreads function calls.
|
- A common thread call is thread_yield, which allows a thread to voluntarily give up the CPU to let another thread run.
- Such a call is important because there is no clock interrupt to actually enforce time-sharing as there is with processes.
- Thus it is important for threads to be polite and voluntarily surrender the CPU from time to time to give other threads a chance to run.
- The C program shown below demonstrates the basic Pthreads API for constructing a multithreaded program that calculates the summation of a nonnegative integer in a separate thread (do not forget to compile with -lpthread flag.).
- In a Pthreads program, separate threads begin execution in a specified function (in this program; ).
#include <pthread.h>
#include <stdio.h>
int sum; /* this data is shared by the thread(s) */
void *runner(void *param); /* the thread */
int main(int argc, char *argv[])
{
pthread_t tid; /* the thread identifier */
pthread_attr_t attr; /* set of thread attributes */
if (argc != 2) {
fprintf(stderr, "usage: a.out <integer value>\n");
return -1;
}
if (atoi(argv [1]) < 0) {
fprintf(stderr,"%d must be >= O\n",atoi(argv[1]));
return -1;
}
/* get the default attributes */
pthread_attr_init (&attr);
/* create the thread */
pthread_create(&tid,&attr,runner,argv[1]) ;
/* wait for the thread to exit */
pthread_join(tid,NULL) ;
printf (" sum = %d\n", sum) ;
}
/* The thread will begin control in this function */
void *runner(void *param)
{
int i, upper = atoi(param);
sum = 0;
for (i = 1; i <= upper; i++)
sum += i;
pthread_exit(0) ;
}
Cem Ozdogan
2010-03-15