Pthreads(POSIX Threads)參考 POSIX 標準定義執行緒產生和同步的API,是執行緒行為規格,而非製作。主要在Unix和類Unix系統(如Linux和macOS)中使用。它提供了一組函數來創建和管理線程,使得開發者可以在應用程式中實現並行處理。
thrd-posix.c
/**
* A pthread program illustrating how to
* create a simple thread and some of the pthread API
* This program implements the summation function where
* the summation operation is run as a separate thread.
*
* Most Unix/Linux/OS X users
* gcc thrd.c -lpthread
*
* Solaris users must enter
* gcc thrd.c -lpthreads
*
* Figure 4.9
*
* @author Gagne, Galvin, Silberschatz
* Operating System Concepts - Ninth Edition
* Copyright John Wiley & Sons - 2013
*/
#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[]) /* 當程式啟動時,OS創建並執行主線程,並進入 main 函數 */
{
pthread_t tid; /* the thread identifier */
pthread_attr_t attr; /* set of attributes for the thread */
if (argc != 2) {
fprintf(stderr,"usage: a.out <integer value>\n");
/*exit(1);*/
return -1;
}
/* 命令行參數檢查 */
if (atoi(argv[1]) < 0) {
fprintf(stderr,"Argument %d must be non-negative\n",atoi(argv[1]));
/*exit(1);*/
return -1;
}
/* get the default attributes 初始化線程屬性 */
pthread_attr_init(&attr);
/* create the thread 創建子線程 */
pthread_create(&tid,&attr,runner,argv[1]);
/* now 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;
if (upper > 0) {
for (i = 1; i <= upper; i++)
sum += i;
}
pthread_exit(0);
}
Terminal
編譯並執行
gcc thrd-posix.c -lpthread
./a.out 10
結果:
參考:greggagne/OSC9e/ch4/thrd-posix.c
More:並行程式設計: 概念