pthread mutex 属性

mutex互斥锁有四种属性,分别是NORMAL, ERRORCHECK, RECURSIVE, DEFAULT,通过pthread_mutexattr_settype 对互斥锁进行属性设置。

PTHREAD_MUTEX_NORMAL

This type of mutex does not detect deadlock. A thread attempting to relock this mutex without first unlocking it shall deadlock. Attempting to unlock a mutex locked by a different thread results in undefined behavior. Attempting to unlock an unlocked mutex results in undefined behavior.

PTHREAD_MUTEX_ERRORCHECK

This type of mutex provides error checking. A thread attempting to relock this mutex without first unlocking it shall return with an error. A thread attempting to unlock a mutex which another thread has locked shall return with an error. A thread attempting to unlock an unlocked mutex shall return with an error.

PTHREAD_MUTEX_RECURSIVE

A t

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
pthread_mutex_t是Linux线程中用于实现互斥的数据类型。它可以确保在多线程环境下对共享资源的访问是互斥的,避免了数据竞争的问题。 在使用pthread_mutex_t之前,需要先进行初始化。可以使用pthread_mutex_init函数进行初始化,该函数的原型如下: ```c int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr); ``` 其中,mutex是要初始化的互斥量对象,attr是互斥量的属性,可以为NULL表示使用默认属性。 初始化完成后,可以使用pthread_mutex_lock函数对互斥量进行加,该函数的原型如下: ```c int pthread_mutex_lock(pthread_mutex_t *mutex); ``` 该函数会阻塞当前线程,直到成功获取到互斥量的。如果互斥量已经被其他线程定,则当前线程会被阻塞,直到互斥量被解。 另外,还可以使用pthread_mutex_trylock函数尝试对互斥量进行加,该函数的原型如下: ```c int pthread_mutex_trylock(pthread_mutex_t *mutex); ``` 该函数会尝试对互斥量进行加,如果互斥量已经被其他线程定,则函数会立即返回一个非零值,表示加失败。 最后,使用pthread_mutex_unlock函数对互斥量进行解,该函数的原型如下: ```c int pthread_mutex_unlock(pthread_mutex_t *mutex); ``` 该函数会解互斥量,允许其他线程获取到互斥量的。 总结起来,pthread_mutex_t是Linux线程中用于实现互斥的数据类型,通过pthread_mutex_init、pthread_mutex_lock、pthread_mutex_trylock和pthread_mutex_unlock等函数可以对互斥量进行初始化、加和解操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值