创建线程,并等待线程执行完成,回收线程的资源
void* thread_fun(void *arg)
{
printf("thread_fun start\n");
int i;
for (i = 0; i < 3; ++i) {
printf("I am %lx ------ %d\n", pthread_self(), i);
usleep(1000);
}
printf("thread_fun end\n");
}
int main() {
pthread_t thread;
int ret = pthread_create(&thread, NULL, thread_fun, NULL);
printf("mpthread_join...\n");
//等待线程执行完成
pthread_join(thread, NULL);
printf("pthread_join end\n");
return 0;
}
编译
gcc main.c -lpthread -o thread
执行结果
由于pthread库不是Linux系统默认的库,连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时,在编译中要加-lpthread参数:
gcc -o pthread -lpthread pthread.c
如果还不对,很有可能是-lpthread放置的位置不对:
gcc pthread.c -lpthread -o pthread
设置线程分离
线程分离状态:指定该状态,线程主动与主控线程断开关系。使用pthread_exit或者线程自动结束后,其退出状态不由其他线程获取,而直接自己自动释放。网络、多线程服务器常用。
在线程thread_fun中设置线程分离
void* thread_fun(void *arg)
{
//设置线程为分离属性
pthread_detach(pthread_self());
printf("thread_fun start\n");
int i;
for (i = 0; i < 3; ++i) {
printf("I am %lx -- %d\n", pthread_self(), i);
usleep(1000);
}
printf("thread_fun end\n");
}
int main() {
pthread_t thread;
int ret = pthread_create(&thread, NULL, thread_fun, NULL);
printf("mpthread_join...\n");
//子线程设置分离属性,则pthread_join不再阻塞,立刻返回
ret=pthread_join(thread, NULL);
if(ret!=0)
printf("pthread_join error \n");
printf("pthread_join end\n");
return 0;
}
执行结果如下
创建线程的时候通过属性设置线程分离
void* thread_fun(void *arg)
{
printf("thread_fun start\n");
int i;
for (i = 0; i < 3; ++i) {
printf("I am %lx -- %d\n", pthread_self(), i);
usleep(1000);
}
printf("thread_fun end\n");
}
int main() {
//定义pthread_attr_t类型的变量
pthread_attr_t attr;
//初始化attr变量
pthread_attr_init(&attr);
//设置attr为分离属性
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
//创建子线程
pthread_t thread;
int ret = pthread_create(&thread, &attr, thread_fun, NULL);
//释放线程属性
pthread_attr_destroy(&attr);
printf("mpthread_join...\n");
//子线程设置分离属性,则pthread_join不再阻塞,立刻返回
ret=pthread_join(thread, NULL);
if(ret!=0)
printf("pthread_join error \n");
printf("pthread_join end\n");
return 0;
}
执行结果如下
创建线程之后设置线程分离
void* thread_fun(void *arg)
{
printf("thread_fun start\n");
int i;
for (i = 0; i < 3; ++i) {
printf("I am %lx -- %d\n", pthread_self(), i);
usleep(1000);
}
printf("thread_fun end\n");
}
int main() {
pthread_t thread;
int ret = pthread_create(&thread, NULL, thread_fun, NULL);
//设置线程为分离属性
pthread_detach(thread);
printf("mpthread_join...\n");
//子线程设置分离属性,则pthread_join不再阻塞,立刻返回
ret=pthread_join(thread, NULL);
if(ret!=0)
printf("pthread_join error \n");
printf("pthread_join end\n");
return 0;
}
执行结果如下