Pthreads는 스레드 생성 및 동기화를 위한 API를 정의하는 POSIX 표준(IEEE 1003.1c)을 나타냅니다. 이것은 구현이 아니라 스레드 동작에 대한 사양을 정의합니다. 사양은 OS 디자이너가 원하는 방식으로 구현할 수 있습니다. 많은 시스템이 Pthread 사양을 구현합니다. 대부분은 Linux, Mac OS X 및 Solaris를 포함한 UNIX 유형 시스템입니다. Windows는 기본적으로 Pthread를 지원하지 않지만 Windows용 일부 타사 구현을 사용할 수 있습니다. 그림 4.9에 표시된 C 프로그램은 별도의 스레드에서 음이 아닌 정수의 합을 계산하는 다중 스레드 프로그램을 구성하기 위한 기본 Pthreads API를 보여줍니다. 별도의 스레드는 Pthreads 프로그램의 지정된 함수에서 실행을 시작합니다. 아래 프로그램에서 이것은 runner() 함수입니다. 이 프로그램이 시작될 때 제어의 단일 스레드는 main()에서 시작됩니다. 그런 다음 main()은 일부 초기화 후에 runner() 함수에서 제어를 시작하는 두 번째 스레드를 만듭니다. 두 스레드 모두 전역 데이터 합계를 공유합니다.
예시
#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);
} Pthreads API를 사용하는 다중 스레드 C 프로그램.