<aside>
💡 pthread_create
为调用进程创建一个子线程
</aside>
一般情况,main函数所在的线程称之为主线程/main线程。其余创建的线程称之为子线程
参数
thread
:传出参数,线程创建成功后子线程的线程ID会被写到该变量中attr
:传入参数,用于设置线程的属性,一般使用默认值(NULL)
start_routine
:函数指针,指向子线程需要处理的逻辑代码arg
:传给start_routine函数的参数返回值
thread
参数变为未定义的
char* strerror(int errnum)
例子
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
void * callback(void * arg) {
printf("child thread...\\n");
printf("arg value: %d\\n", *(int *)arg);
return NULL;
}
int main() {
pthread_t tid;
int num = 10;
// 创建一个子线程
int ret = pthread_create(&tid, NULL, callback, (void *)&num);
if(ret != 0) {
char * errstr = strerror(ret);
printf("error : %s\\n", errstr);
}
// 主线程执行的内容
for(int i = 0; i < 5; i++) {
printf("%d\\n", i);
}
// 让主线程退出,当主线程退出时,不会影响其他正常运行的线程。
// 防止子线程还没创建好主线程就exit了
pthread_exit(NULL);
return 0; // exit(0);
}
<aside>
💡 pthread_self
用于获取当前线程的线程ID
</aside>
<aside>
💡 pthread_exit
用于终止一个线程,在哪个线程中调用就终止哪个线程
</aside>