pthread_exit函数

void pthread_exit(void *retval); 参数:retval表示线程退出状态,通常传NULL。

作用:将单个线程退出。

注意几点:

  1. return的作用是返回到函数的调用点,如果是main函数中的return,则代表该进程结束,并释放进程地址空间,所有线程都终止。对于其它函数的return,则直接返回到函数的调用点。exit和_exit函数会直接终止整个进程,导致所有线程结束。pthread_exit函数则会导致调用该函数的线程结束。所以,多线程环境中,应尽量少用,或者不使用exit函数,取而代之使用pthread_exit函数,将单个线程退出。任何线程里exit导致进程退出,其他线程也结束,主控线程退出时不能return或exit。
  2. 另注意,pthread_exit或者return返回的指针(线程执行的函数用return或者pthread_exit结束线程时)所指向的内存单元必须是全局的或者是用malloc分配的,不能在线程函数的栈上分配,因为当其它线程得到这个返回指针时线程函数已经退出了,此时退出的这个线程函数所占据的栈空间可能又会被重新分配出去,因此其他线程再次使用这个返回的地址没有意义。

//代码示例

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void *tfn(void *arg)
{
        int s = (int)arg;

        printf("The %dth thread: the process id is %d and thread id is %lu.\n",s+1,getpid( ),pthread_self( ));

        return NULL;
}

int main(int argc,char *argv[ ])
{
        pthread_t tid;
        int ret, i, n=5;

        if(argc == 2)
            n = atoi(argv[1]);

        for( i=0;i<n;i++ )
        {
            ret = pthread_create(&tid, NULL, tfn,(void *)i);
            if( ret != 0 )
            {
                fprintf(stderr,"pthread_create error: %s\n",strerror(ret));
                exit(1);
            }
        }

        printf("In main: the process id is %u and thread id is %lu.\n",getpid( ),pthread_self( ));

        pthread_exit( NULL );
}

[root@localhost 01_pthread_test]# ./pthrd_crt 10

The 1th thread: the process id is 9035 and thread id is 4149640000.

The 4th thread: the process id is 9035 and thread id is 4124461888.

The 7th thread: the process id is 9035 and thread id is 4099283776.

The 9th thread: the process id is 9035 and thread id is 4082498368.

In main: the process id is 9035 and thread id is 4151699712.

The 6th thread: the process id is 9035 and thread id is 4107676480.

The 8th thread: the process id is 9035 and thread id is 4090891072.

The 5th thread: the process id is 9035 and thread id is 4116069184.

The 10th thread: the process id is 9035 and thread id is 4074105664.

The 2th thread: the process id is 9035 and thread id is 4141247296.

The 3th thread: the process id is 9035 and thread id is 4132854592.

分析:通过使用pthread_exit函数可以不再用sleep函数,此时线程输出的顺序也是无序的。

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值