pthread可以创建线程
头文件
#include<pthread.h>
pthread_t tid:声明了所创建线程的标识符
pthread_attr_t attr:表示线程的属性
pthread_attr_init(&attr):设置线程的属性
pthread_create:创建一个独立线程
函数声明
int pthread_create(pthread_t* restrict tidp,const pthread_attr_t* restrict_attr,void* (start_rtn)(void),void *restrict arg);
- tidp:新创建的线程的标识符
- attr:线程属性,一般设置为NULL
- satrt_rtn:新创线程从此开始运行
- arg:start_rtn函数的参数
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 4
void* threadfunc(void *r) {
printf("This is a pthread %d.\n", *(int*)r);
pthread_exit(0);
}
int main(void) {
pthread_t workers[NUM_THREADS];
int i, ret;
int data[NUM_THREAD] = {1,2,3,4};
for (i = 0; i < NUM_THREADS; ++i){
ret = pthread_create(&workers[i], NULL, threadfunc, (void*)&data[i]);
if (ret != 0){
printf("Create pthread %d error!\n", i);
return 1;
}
}
printf("This is the main process.\n");
for (i = 0; i < NUM_THREADS; ++i)
pthread_join(workers[i], NULL);
return 0;
}