POSIX Thread Libraries

Operating SystemWindowsLinuxC

Pthreads refers to the POSIX standard (IEEE 1003.1c) defining an API for thread creation and synchronization. This defines specification for thread behavior, not an implementation. The specification can be implemented by OS designers in any way they wish. So many systems implement the Pthreads specification; most are UNIX-type systems, including Linux, Mac OS X, and Solaris. Although Windows doesn’t support Pthreads natively, some third-party implementations for Windows are available. The C program shown in Figure 4.9 demonstrates the basic Pthreads API for constructing a multithreaded program that calculates the summation of a nonnegative integer in a separate thread. Separate threads begin execution in a specified function in a Pthreads program. In below program, this is the runner() function. At the time when this program begins, a single thread of control begins in main().Then main() creates a second thread that begins control in the runner() function, after some initialization,. Both threads share the global data sum.

Example

#include<pthread.h>
#include<stdio.h>
int sum;
/* this sum data is shared by the thread(s) */
/* threads call this function */
void *runner(void *param);
int main(int argc, char *argv[]){
   pthread t tid; /* the thread identifier */
   /* set of thread attributes */
   pthread attr t attr;
   if (argc != 2){
      fprintf(stderr,"usage: a.out \n");
      return -1;
   }
   if (atoi(argv[1]) < 0){
      fprintf(stderr,"%d must be >= 0\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 now 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);
}

Multithreaded C program using the Pthreads API.

raja
Published on 17-Oct-2019 12:18:35
Advertisements