简单来说:
pthread_detach()即主线程与子线程分离,子线程结束后,资源自动回收。
pthread_join()即是子线程合入主线程,主线程阻塞等待子线程结束,然后回收子线程资源.
创建线程,设置线程名字,设置分离状态:
pthread_t thread;
pthread_create(&thread, NULL, &state, NULL);
pthread_setname_np(thread, "thread1");
pthread_detach(thread);
pthread_join的用法:
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
void *thread_function(void *arg)
{
int i;
for ( i=0; i<8; i++)
{
printf("Thread working...! %d \n",i);
sleep(1);
}
return NULL;
}
int main(void)
{
pthread_t mythread;
if ( pthread_create( &mythread, NULL, thread_function, NULL) )
{
printf("error creating thread.");
abort();
}
if ( pthread_join ( mythread, NULL ) )
{
printf("error join thread.");
abort();
}
printf("thread done! \n");
exit(0);
}
pthread_detach()的用法:
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/types.h>
#include <dirent.h>
#include <pthread.h>
#include <errno.h>
#include <signal.h>
#include <time.h>
void* thread1(void *arg)
{
while (1)
{
usleep(100 * 1000);
printf("thread1 running...!\n");
}
printf("Leave thread1!\n");
return NULL;
}
int main(int argc, char** argv)
{
pthread_t tid;
pthread_create(&tid, NULL, (void*)thread1, NULL);
pthread_detach(tid); // 使线程处于分离状态
sleep(1);
printf("Leave main thread!\n");
pthread_exit("end"); //这个地方执行后,子进程并没有退出
// return 0; //return后,系统会调用_exit,所有进程都会退出。
}
#gcc a.c -lpthread
#./a.out
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
Leave main thread!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
可以看出main线程退出后,thread_1并没有退出。
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/types.h>
#include <dirent.h>
#include <pthread.h>
#include <errno.h>
#include <signal.h>
#include <time.h>
void* thread1(void *arg)
{
while (1)
{
usleep(100 * 1000);
printf("thread1 running...!\n");
}
printf("Leave thread1!\n");
return NULL;
}
int main(int argc, char** argv)
{
pthread_t tid;
pthread_create(&tid, NULL, (void*)thread1, NULL);
pthread_detach(tid); // 使线程处于分离状态
sleep(1);
printf("Leave main thread!\n");
return 0;
}
$ ./a.out
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
thread1 running...!
Leave main thread!
可以看出main线程return后,子线程也退出了。