android下pthread相关概念理解

来源:互联网 发布:新开的淘宝店怎么找货 编辑:程序博客网 时间:2024/06/06 16:38

1.结构体理解

pthread_t

pthread_attr_t



2.create

//创建线程, 成功 返回0, 出错返回-1

//第一个参数为线程id指针,用于存放创建好的线程的id值。

//第二个为线程属性。它来源于POSIX线程库。对应linux,android,设置成null即可。作为gcc标准方法使用时,它可以传递很多参数,比如:PTHREAD_CREATE_JOINABLE,PTHREAD_CREATE_DETACH等。

//第三个函数是函数指针,用于指向子线程的操作函数。

//最后一个是传统的参数指针,用于传递参数。

int

pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr,

               void *(*start_routine)(void *),void *restrict arg);



3.获取pid

//以下是pthread_self的gcc 描述。用于在线程内部需要传入自身pid时获取pid的方式,一般和detach一起使用。

//DESCRIPTION

//The pthread_self() function returns the thread ID of the calling thread.)

pthread_t

pthread_self(void);

//需要注意的是gettid()与它的区别



4.回收

//下面是gcc的说明,很好理解,当前线程挂起等待,直到需要回收的线程结束。

//DESCRIPTION

//The pthread_join() function suspends execution of the calling thread

//until the target thread terminates, unless the target thread has already

//terminated.)

int

pthread_join(pthread_t thread, void **value_ptr);



5. atach detach

//在理解atach和detach之前,要先理解joinable, unjoinable。

//如果线程是joinable状态,当线程函数自己返回退出时(不论是否调用pthread_exit),不会释放线程所占用堆栈和线程描述符(在标准gcc环境中,大概8k多)。只有当主线程显示调用了pthread_join之后这些资源才会被释放。

//如果线程是unjoinable状态,在线程函数退出时(或者手动调用了pthread_exit时),这些资源会被释放。

//如果是标准gcc, joinable, unjoinable属性可以在pthread_create时指定。设置 pthread_addr 为 PTHREAD_CREATE_JOINABLE,PTHREAD_CREATE_DETACH。

//如果是android等其他衍生标准,最好使用第二种方式来进行资源管理:

//pthread_detach(pthread_self()),会将状态改为unjoinable状态,确保资源的释放。或者我们可以把线程设置为joinable,然后在适当的时候调用pthread_join。

//如果是标准gcc代码,在函数头加上pthread_detach(pthread_self()),把状态变成unjoinable,然后在结束时调用pthread_exit,线程就会自动退出。


//由attach, detach衍生出来的,当我们实现c/c++和java混合调用时,需要调用到 AttachCurrentThread(), DetachCurrentThread()。



6.

pthread_cancel

取消线程


7.线程等待和唤醒,pthread_cond_wait, pthread_cond_signal。 可以参考百度,这是个很经典的例子。

https://baike.baidu.com/item/pthread_cond_wait/3011997?fr=aladdin