多线程程序的编译时,一定记得要加入动态库,例如:gcc k.c -o k -lpthread,但运行时却不用加。
首先#include <pthread.h>。
线程的创建:int pthread_create(&线程名字,NULL,线程执行函数名,传递的参数*arg),执行函数必须是这种:void *func(),可以带参数,也可以不带,函数体随意。成功则返回0。
线程的等待(所谓等待,就是函数名称的字面意思):int pthread_join(直接是线程名字,保存线程返回值的指针void **returnValue)。成功则返回0。
线程的退出:void pthread_exit(void *returnValue),返回值就是一个字符串,可以由其他函数,如等待函数pthread_join来检测获取其返回值。
复制代码
//这是最简单的使用了
#include <stdio.h>
#include <pthread.h>
void *func(void *arg)
{
printf("arg=%d\n", *(int *)arg);
pthread_exit("bye bye");
}
int main()
{
int res;
pthread_t first_thread;
int share_int = 10;
res = pthread_create(&first_thread, NULL, func, (void *)&share_int);
printf("res=%d\n", res);
void *returnValue;
res = pthread_join(first_thread, &returnValue);
printf("returnValue=%s\n", (char *)returnValue);
return 0;
}