pthread_create()
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
第一个参数表示线程id, 第二个参数表示该线程的属性(?),
第三个参数表示该线程的启动函数,第四个参数表示传入参数
线程创建之后,如果应该使用pthread_join函数对这个线程进行回收的。
pthread_join
pthread_join函数使用阻塞的方式,使得使线程结束以回收资源。
当不希望阻塞时,可以使用:
pthread_detach(pthread_self())//使线程自己结束后自动回收资源
pthread_detach(tid)//希望tid的线程号结束后自动回收资源,这样不会产生僵死进程
示例代码
#include "apue.h"
void *thread_fun()
{
printf("new thread is running!\n");
sleep(2);
return (void *)0;
}
int main()
{
pthread_t tid;
int err;
err = pthread_create(&tid, NULL, thread_fun, NULL);
if(err != 0)
{
printf("create thread failed!\n");
return -1;
}
//pthread_join(tid, NULL);
pthread_detach(tid);
return 0;
}
喜欢 (0)or分享 (0)