实现POSIX线程标准的库常被称作pthreads,一般用于Unix-like POSIX 系统,如Linux、 Solaris。pthreads定义了一套C语言的类型、函数与常量,它以pthread.h头文件和一个线程库实现。
一、 pthread_create():创建一个线程
#include <pthread.h> int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg); // pthread_create - create a new thread
pthread_t:线程句柄。出于移植目的,不能把它作为整数处理,应使用函数pthread_equal()对两个线程ID进行比较。获取自身所在线程id使用函数pthread_self()。
pthread_attr_t:线程属性。主要包括scope属性、detach属性、堆栈地址、堆栈大小、优先级。
二、 pthread_join():阻塞当前的线程,直到另外一个线程运行结束
#include <pthread.h> int pthread_join(pthread_t thread, void **retval); // pthread_join - join with a terminated thread
三、 创建线程示例
#include <stdio.h> #include <unistd.h> #include <pthread.h> #include <stdlib.h> void *thread_run(void *arg) { int t = *(int *)arg; for(int i=0; i<5; i++) { printf("The new thread %d\n", t); } return NULL; } int main(void) { pthread_t tid[5]; int param[5]; int retval; for(int i=0; i<5; i++) { param[i] = i + 1; // 创建线程,并传递参数 retval = pthread_create(&tid[i], NULL, thread_run, (void *)¶m[i]); // 创建线程失败 if(retval != 0) { printf("pthread create error\n"); exit(1); } } for(int i=0; i<5; i++) { // 阻塞主线程 retval = pthread_join(tid[i], NULL); // 阻塞主线程失败 if(retval != 0) { printf("pthread join error\n"); exit(1); } } return 0; }
四、 运行结果
[ycxie@fedora Workspace]$ gcc pthread_create_demo.c -o pthread_create_demo -pthread -Wall [ycxie@fedora Workspace]$ ./pthread_create_demo The new thread 1 The new thread 1 The new thread 1 The new thread 1 The new thread 1 The new thread 2 The new thread 2 The new thread 2 The new thread 2 The new thread 2 The new thread 5 The new thread 4 The new thread 4 The new thread 4 The new thread 4 The new thread 4 The new thread 5 The new thread 5 The new thread 5 The new thread 5 The new thread 3 The new thread 3 The new thread 3 The new thread 3 The new thread 3 [ycxie@fedora Workspace]$ ./pthread_create_demo The new thread 5 The new thread 4 The new thread 2 The new thread 2 The new thread 2 The new thread 2 The new thread 2 The new thread 5 The new thread 5 The new thread 5 The new thread 5 The new thread 3 The new thread 3 The new thread 3 The new thread 3 The new thread 3 The new thread 4 The new thread 4 The new thread 4 The new thread 1 The new thread 1 The new thread 1 The new thread 1 The new thread 1 The new thread 4