首页 > 编程语言 > 详细

多线程同步精要

时间:2017-09-16 12:43:00      阅读:236      评论:0      收藏:0      [点我收藏+]

单机并发编程有两种基本模型:"消息传递"和"共享内存";分布式系统运行在多台机器上,只有一种实用模型:"消息传递"。

单机上多进程并发可以照搬"消息传递",多线程编程用"消息传递"更容易保证程序的正确性。

多线程同步有很多种方式:互斥量、条件变量、信号量、读写锁等。尽量不要用信号量和读写锁

Don’t use a semaphore where a mutex would suffice. A semaphore is a generic synchronization primitive originally described by Dijkstra that can be used to effect a wide range of behavior. It may be tempting to use semaphores in lieu of mutexes to protect critical sections, but there is an important difference between the two constructs: unlike a semaphore, a mutex has a notion of ownership—the lock is either owned or not, and if it is owned, it has a known owner. By contrast, a semaphore (and its kin, the condition variable) has no notion of ownership: when sleeping on a semaphore, one has no way of knowing which thread one is blocking upon.(引自《Real-World Concurrency》http://queue.acm.org/detail.cfm?id=1454462)

信号量的另一个问题是:它有自己的计数值,通常我们自己的数据结构也有长度值,这就造成了同样的信息存了两份,这就需要时刻保持一致,增加了程序员的负担和出错的可能。

mutex和condition variable是用的最多的,用他们两个足以应对大多数的使用场景。

互斥量mutex

原则:

1.利用RAII自动创建、销毁、加锁、解锁,不手动调用lock() unlock()函数。

2.只用在线程同步中,不用跨进程的mutex。

3.首选非递归mutex(不可重入mutex)。附:windows的CRITICAL_SECTION是可重入的,linux下mutex默认是不可重入的。不可重入mutex的优点是:在同一个线程里多次对non-recursive mutex加锁会立刻导致死锁,这能够帮助我们思考代码对锁的期求,并且及早(在编码阶段)发现问题。

多线程同步精要

原文:http://www.cnblogs.com/xuelei/p/7530615.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!