欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 幼教 > Linux C-线程相关函数1

Linux C-线程相关函数1

2024/10/23 23:20:13 来源:https://blog.csdn.net/tjzhuorui/article/details/143062382  浏览:    关键词:Linux C-线程相关函数1

1、线程 thread

1.1 线程的创建 pthread_create

函数原型:int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);

重要参数

        1、start_routine 子线程运行的函数名

        2、arg 传递参数的指针

返回值

        成功:0

        失败:其他

1.2 线程的回收

1.2.1 pthread_join

函数原型:int pthread_join(pthread_t thread, void **retval);

函数描述:阻塞式等待指定线程的结束

重要参数

返回值

        成功:0

        失败:其他

1.2.2 pthread_detach

函数原型:int pthread_detach(pthread_t thread);

函数描述:非阻塞式,当指定线程结束时,系统自动回收线程资源

重要参数

返回值

        成功:0

        失败:其他

1.3 线程的退出 pthread_exit

函数原型:void pthread_exit(void *retval);

重要参数

        1、retval 与pthread_join配合使用,用于接收退出状态的返回值

返回值

        无

1.4 获取当前线程号 pthread_self

函数原型:pthread_t pthread_self(void);

重要参数

返回值

2、互斥锁 mutex

1.1 互斥锁初始化 pthread_mutex_init

函数原型:int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr);

重要参数

        1、mutex: pthread_mutex_t mutex

返回值

        成功:0

        失败:其他

1.2 上锁 

1.2.1 pthread_mutex_lock

函数原型:int pthread_mutex_lock(pthread_mutex_t *mutex);

函数描述:阻塞式

重要参数

返回值

        成功:0

        失败:其他

1.2.2 phtread_mutex_trylock

函数原型:int pthread_mutex_trylock(pthread_mutex_t *mutex);

函数描述:非阻塞式

重要参数

返回值

        成功:0(获取到锁)

        失败:其他

1.3 解锁 pthread_mutex_unlock

函数原型:int pthread_mutex_unlock(pthread_mutex_t *mutex);

重要参数

返回值

        成功:0

        失败:其他

1.4 销毁互斥锁 pthread_mutex_destroy

函数原型:int pthread_mutex_destroy(pthread_mutex_t *mutex);

重要参数

返回值

        成功:0

        失败:其他

3、信号量 semaphore

3.1 创建信号量 sem_create

函数原型:int sem_init(sem_t *sem, int pshared, unsigned int value);

重要参数

        1、pshare: 0-线程间  1-进程间

        2、value:信号量的值

返回值

        成功:0

        失败:-1

3.2 通知post

函数原型:int sem_post(sem_t *sem);

重要参数

返回值

        成功:0

        失败:-1

3.3 等待通知wait

函数原型:int sem_wait(sem_t *sem);

重要参数:阻塞式

返回值

        成功:0

        失败:-1

3.4 销毁信号量

函数原型:int sem_destroy(sem_t *sem);

重要参数

返回值

        成功:0

        失败:-1

疑问及待验证的问题:

1、线程的创建和使用

1.1、Linux c有类似java一样的线程池吗

1.2、pthread_exit的retval如何使用,目前还不太明白。

2、互斥锁

2.1、mutex锁静态构建的方法

3、信号量

3.1、一个线程post,多个线程wait

3.2、多个线程post,一个线程wait

3.3、多个线程post,多个线程wait

3.4、如何获取信号量的值,sem_t的value,以及最大值是多少

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com