Android C++系列:Linux线程(二)线程原语

1. 创建线程 pthread_create

#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);

Compile and link with -lpthread. 
typedef unsigned long int pthread_t;
  • pthread_t *thread:传递一个pthread_t变量地址进来,用于保存新线程的tid(线程ID)
  • const pthread_attr_t *attr:线程属性设置,如使用默认属性,则传NULL
  • void *(*start_routine) (void *):函数指针,指向新线程应该加载执行的函数模块
  • void *arg:指定线程将要加载调用的那个函数的参数 返回值:成功返回0,失败返回错误号。之前介绍的系统函数都是成功返回0,失败返回-1,而错误号保存在全局变 量errno中,而pthread库的函数都是通过返回值返回错误号,虽然每个线程也都有一个errno,但这是为了兼容其 它函数接口而提供的,pthread库本身并不使用它,通过返回值返回错误码更加清晰。

在一个线程中调用pthread_create()创建新的线程后,当前线程从pthread_create() 返回继续往下执行,而新的线程所执行的代码由我们传给pthread_create的函数指针 start_routine 决 定。start_routine 函 数 接 收 一 个 参 数, 是 通 过 pthread_create 的 arg 参 数传递给它的,该参数的类型为void *,这个指针按什么类型解释由调用者自己定 义。start_routine的返回值类型也是void *,这个指针的含义同样由调用者自己定义。start_routine 返回时,这个线程就退出了,其它线程可以调用pthread_join得到start_routine的返回值,类似于父进程调用wait(2)得到子进程的退出状态,下面会详细介绍pthread_join。

pthread_create成功返回后,新创建的线程的id被填写到thread参数所指向的内存单元。我们知道进程id的类型是pid_t,每个进程的id在整个系统中是唯一的&

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

轻口味

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值