Linux中pthread函数的使用

pthread_crete()

函数原型说明

头文件:pthread.h
函数原型:int pthread_create(pthread_t *tid, const pthread_attr_t attr,
(void
)(start_rtn)(void), void *arg);

功能:创建一个新的线程.

返回值:0:成功.
-1:若线程创建失败,则返回出错编号.

参数1:用于保存线程ID的变量地址.
注:typedef long unsigned int pthread_t;
参数2:新建线程的属性
参数3:线程代码的地址.
参数4:参数地址.

pthread_join()

函数原型说明

头文件:pthread.h
函数原型: int pthread_join(pthread_t thread, void **retval);;

功能:阻塞当前线程,等待目标线程结束,然后回收目标线程的资源。
【阻塞等待回收指定线程的资源】

返回值: 成功: 0
失败: 错误号

参数1:目标线程ID.
参数2:用于保存目标线程返回值的变量的指针.
主要作用:
pthread_join()主要有两种作用:
1)同步:当调用pthread_join()时,当前线程会处于阻塞状态,直到被调用的线程结束后,当前线程才会重新开始执行.
2)对线程的资源进行回收:如果一个线程是joinable的(默认情况下创建的线程都是joinable的),并且没有对该线程使用
pthread_join(),那么该线程结束后并不会释放其内存空间,这会导致该线程变成了“僵尸线程”.

manual pthread_join 描述:
The pthread_join() function waits for the thread specified by thread to terminate.
If that thread has already terminated, then pthread_join() returns immediately.
The thread specified by thread must be joinable.
当前线程进入pthread_join()函数中,pthread_join()等待指定线程结束才会返回。
如果指定线程已经结束,则pthread_join立即返回。
指定线程必须处于joinable状态。

If retval is not NULL, then pthread_join() copies the exit status of the target thread (i.e., the value that the target thread supplied to pthread_exit(3)) into the location pointed to by retval.
If the target thread was canceled, then PTHREAD_CANCELED is placed in the location pointed to by retval.
如果目标线程的返回值不是NULL,则pthread_join()会将目标线程的返回值(是一个指针)copy到retval中。
如果目标线程被取消,则PTHREAD_CANCELED被放到retval中。

If multiple threads simultaneously try to join with the same thread, the results are undefined.
If the thread calling pthread_join() is canceled, then the target thread will remain joinable(i.e., it will not be detached).
如果多个线程同时join同一个线程,结果是不确定的。
如果调用pthread_join()被取消,则目标线程任然保持joinable状态。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值