线程
相关函数及过程:
创建线程号; pthread_t tid;
创建线程:pthread_create(&tid, NULL, task, argv[1]);
定义线程执行函数:void *task(void *arg){
线程退出:pthread_exit(ret);//线程结束后退出
}
等待所有线程结束:pthread_join(tid, (void **)&ret);
编译时增加线程库lpthread
代码示例:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h> // atoi, malloc
void *task(void *arg){int n = atoi((char *)arg);int *ret = (int *)malloc(4);// 堆中申请空间, 返回到主线程*ret = 1;for(int i=2;i<=n;i++) *ret *= i;pthread_exit(ret);//线程结束后退出
}int main(int argc,const char *argv[]){if(argc != 2) return -1;pthread_t tid; //创建线程号的变量pthread_create(&tid, NULL, task, argv[1]);// 创建线程并自动启动int *ret = NULL;pthread_join(tid, (void **)&ret); //等待线程全部结束printf("%s != %d\n", argv[1], *ret);if(ret != NULL) free(ret); // 回收空间return 0;
}