Operating System: Three Easy Pieces --- Pthread Locks (Note)

本文深入探讨了POSIX库中互斥锁(mutex)的作用,解释了它们如何提供线程间互斥访问,并强调了通过使用不同锁保护不同变量以提高并发性的方法。文章还对比了粗粒度与细粒度锁定策略的优缺点。

The name that the POSIX library uses for a lock is a mutex, as it is used to provide mutual

exclusion between threads, i.e., if one thread is in the critical section, it excludes the others

from entering until it has completed the section. Thus, when you see the following POSIX

threads code, you should understand that it is doing the same thing as above (we again use

wrappers that check for errors upon lock and unlock):

pthread_mutex_t lock  = PTHREAD_MUTEX_INITITALIZED;

pthread_mutex_lock(&lock);

balance = balance + 1;

pthread_mutex_unlock(&lock);

You might also notice here that the POSIX version passes a variable to lock and unlock, as we

may be using different locks to protect different variables. Doing so can increase concurrency:

instead of one big lock that is used any time any critical section is accessed (a coarse-gained

locking strategy), one will often protect different data and data structures with different locks,

thus allowing more threads to be in locked code at once (a more fine-grained approach).

转载于:https://www.cnblogs.com/miaoyong/p/4910796.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值