Linux 线程退出实例1

 1 #include <stdio.h>

 2 #include <stdlib.h>

 3 #include <string.h>

 4 #include <unistd.h>

 5 #include <semaphore.h>

 6 #include <sys/types.h>

 7 #include <dirent.h>

 8 #include <pthread.h>

 9 #include <errno.h>

10 #include <signal.h>

11 #include <time.h>

12 

13 void* thread1(void *arg)

14 {

15     printf("Leave thread1!\n");

16 

17     return NULL;

18 }

19 

20 int main(int argc, char** argv)

21 {

22     pthread_t tid;

23 

24     pthread_create(&tid, NULL, (void*)thread1, NULL);

25     sleep(1);

26     printf("Leave main thread!\n");

27 

28     return 0;

29 }

程序输出:

[root@robot ~]# gcc thread_not_join.c -lpthread -o thread_not_join

[root@robot ~]# ./thread_not_join

Leave thread1!

Leave main thread!

[root@robot ~]#

这里线程thread1先于主线程退出,但这种情况下会发生什么情况呢?
Linux平台默认情况下,虽然各个线程之间是相互独立的,一个线程的终止不会去通知或影响其他的线程。但是已经终止的线程的资源并不会随着线程的终止而得到释放,我们需要调用 pthread_join() 来获得另一个线程的终止状态并且释放该线程所占的资源。(说明:线程处于joinable状态下

结果:在上述情况下会导致资源泄露,虽然线程thread1是正常退出,并且先于主线程推出。

主线程程序改成如下形式:

    pthread_create(&tid, NULL, (void*)thread1, NULL);
    sleep(1);
    pthread_join(thread1, NULL);  // 保证了线程退出之后回收线程资源
    printf("Leave main thread!\n");

你可能感兴趣的:(linux)