Pthreads หมายถึงมาตรฐาน POSIX (IEEE 1003.1c) ที่กำหนด API สำหรับการสร้างและการซิงโครไนซ์เธรด สิ่งนี้กำหนดข้อกำหนดสำหรับพฤติกรรมของเธรด ไม่ใช่การนำไปใช้ นักออกแบบ OS สามารถนำข้อกำหนดนี้ไปใช้ในลักษณะใดก็ได้ตามต้องการ ระบบจำนวนมากจึงใช้ข้อกำหนด Pthreads ส่วนใหญ่เป็นระบบประเภท UNIX รวมถึง Linux, Mac OS X และ Solaris แม้ว่า Windows จะไม่รองรับ Pthreads แต่มีการนำไปใช้งานของบริษัทอื่นสำหรับ Windows โปรแกรม C ที่แสดงในรูปที่ 4.9 สาธิต 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);
} โปรแกรม C แบบมัลติเธรดโดยใช้ Pthreads API