线程终止——线程的返回值

线程终止

 

如果进程中的任一线程调用了exit,_Exit或者_exit,那么整个进程就会终止。与此类似,如果信号的默认动作是终止进程,那么,把该信号发送到线程会终止整个进程。

单个线程可以通过下列三种方式退出,在不终止整个进程的情况下停止它的控制流。

(1):从启动例程中返回,返回值是线程的退出码

(2):线程可以被同一进程中的其他线程取消

(3):线程调用pthread_exit()

 

 pthread_exit函数:

  • 原型: void pthread_exit(void *rval_ptr);
  • 头文件: <pthread.h>
  • 参数: rval_ptr是一个无类型指针, 指向线程的返回值存储变量.

 pthread_join函数:

  • 原型: int pthread_join(pthread_t thread, void **rval_ptr);
  • 头文件: <pthread.h>
  • 返回值: 成功则返回0, 否则返回错误编号.
  • 参数:
    • thread: 线程ID.
    • rval_ptr: 指向返回值的指针(返回值也是个指针).
  • 说明:
    • 调用线程将一直阻塞, 直到指定的线程调用pthread_exit, 从启动例程返回或被取消.
    • 如果线程从它的启动例程返回, rval_ptr包含返回码.
    • 如果线程被取消, 由rval_ptr指定的内存单元置为: PTHREAD_CANCELED.
    • 如果对返回值不关心, 可把rval_ptr设为NULL.

实例:

#include <pthread.h>

#include <stdio.h>

 

 

/* print process and thread IDs */

void printids(const char *s)

{

   pid_t pid, ppid;

   pthread_t tid;

 

    pid= getpid();

   ppid = getppid();

   tid = pthread_self();

 

   printf("%16s pid %5u ppid %5u tid %16u (0x%x) ",

            s, (unsigned int)pid, (unsigned int)ppid,

            (unsigned int)tid, (unsigned int)tid);

}

 

/* thread process */

void *thread_func(void *arg);

{

   printids("new thread: ");

   return (void *)108;

}

 

/* main func */

int main()

{

   int err;

   void *tret; /* thread return value */

   pthread_t ntid;

 

   err = pthread_create(&ntid, NULL, thread_func, NULL);

   if (err != 0)

       perror("can't create thread");

 

   err = pthread_join(ntid, &tret);

   if (err != 0)

       perror("can't join thread");

 

   printids("main thread: ");

   printf("thread exit code: %d ", (int)tret);

   sleep(1);

 

   return 0;

}

这段代码是通过前一个实例改编的执行流程如下:

  • 首先创建一个新线程, 该线程在打印完IDs后, 返回108.
  • 然后用pthread_join获取该线程返回值, 存于tret中.
  • 主线程打印IDs.
  • 主线程打印tret, 即新线程的返回值.

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值