pthread_create创建线程
一直以来 我都有一个关于posix线程使用的误区
那就是pthread_create
接口创建了线程 但并没有直接启动它
线程的启动必须要由pthread_join
或是pthread_detach
来完成
产生这个误区的主要原因是由于posix的代码通常是这样写的
#include <stdio.h>
#include <pthread.h>
void *funThread(void *args) {
printf("enter %s\n", _func__);
}
int main(int argc, char **argv) {
pthread_t handle;
if (pthread_cerate(&handle, NULL, funThread, NULL) != 0) {
printf("create thread failed\n");
return -1;
}
pthread_join(handle, NULL);
return 0;
}
这样的流程 在posix的demo代码中是最常见的
久而久之 让人产生了 线程是由pthread_join来启动的
并且直接替换pthread_join为pthread_detach 还会发现线程根本没有被运行(由于pthread_detach不阻塞,直接运行到下一句的return 退出了整个程序 造成线程没有被运行的效果)
线程的运行
把代码替换成这样
#include <stdio.h>
#include <pthread.h>
void *funThread(void *args) {
printf("enter %s\n", _func__);
}
int main(int argc, char **argv) {
pthread_t handle;
if (pthread_cerate(&handle, NULL, funThread, NULL) != 0) {
printf("create thread failed\n");
return -1;
}
getchar();
return 0;
}
可以看到线程被正常执行 说明pthread_create创建了线程并使线程投入运行
而且 侧面证明了posix线程的默认属性是detach分离的.