Home  >  Article  >  Backend Development  >  POSIX thread library

POSIX thread library

王林
王林forward
2023-08-25 16:29:06844browse

POSIX thread library

Pthreads refers to the POSIX standard (IEEE 1003.1c), which defines an API for thread creation and synchronization. This defines the specification of thread behavior, not the implementation. Specifications can be implemented by operating system designers in any way they wish. As a result, many systems implement the Pthreads specification; most are UNIX-type systems, including Linux, Mac OS X, and Solaris. Although Windows does not natively support Pthreads, some third-party Windows implementations are available. The C program shown in Figure 4.9 demonstrates the basic Pthreads API for building a multithreaded program that computes the sum of nonnegative integers in separate threads. In a Pthreads program, a separate thread starts executing in a specified function. In the program below, this is the runner() function. When this program starts, a separate thread of control starts in main(). Then, main() creates a second thread, which starts controlling in the runner() function, after some initialization. The two 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 </p><p>");
      return -1;
   }
   if (atoi(argv[1]) < 0){
      fprintf(stderr,"%d must be >= 0</p><p>",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</p><p>",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);
}

Multi-threaded C program using Pthreads API.

The above is the detailed content of POSIX thread library. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete