找回密码
 FreeOZ用户注册
查看: 1165|回复: 0
打印 上一主题 下一主题

Locked-based多线程编程问题

[复制链接]
跳转到指定楼层
1#
发表于 5-8-2009 09:26:15 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?FreeOZ用户注册

x
采用synchronized关键字进行的多线程编程称为locked-based多线程编程,
从1.5开始,Java提供了hardware support non-locked-based多线程编程方案,
可以参考java.util.concurrent.*等几个包。

采用synchronized式的多线程实现方案,除了比较heavy之外,对临界区/临界资源(critical resource)
加锁,会带来下面几种可能性:
1. mutual exclusive(这是正常的)
2. dead lock(死锁)
3. starvation(饿死)
4. priority inversion(优先级倒置)
5. convoy formation/contention(这个不知道怎样翻译)

互斥是加锁的目的,这个就不说了。
dead lock是常见问题,如果两个线程同用两个或以上的锁,线程A取得锁1,等待锁2,
而线程B取得锁2,等待锁1,则会形成死锁。
starvation则是一种活锁问题,著名的例子有哲学家就餐问题:http://zh.wikipedia.org/wiki/哲学家就餐问题

如果哲学家们都拿起左叉来等右叉,则会形成死锁(事实上每个人的左叉是另一个人的右叉,所以相当于锁1和锁2)
如果哲学家们拿起左叉等右叉,等了一个固定时间后放弃,然后又拿起来,就形成一个饿死问题。

哲学家就餐问题可以用介入服务生的方法简单解决,也可以用资源编号的方式进行解决。
在wiki中介绍说,资源编号的方式不实用,其实我们在Java编程时,最常用的就是资源编号的方式。
也就是说,在系统进行加锁的时候,必须按照相同的顺序进行加锁,按相反的顺序进行解锁。
由于编程时我们要手动加的锁是很有限的几个(一般就是一到两个),如果我们能严格地按照这个方法进行
加锁,死锁问题是可以得到解决的。

至于Priority Inversion和Convoy Formation,前者很简单,就是说,通过加锁,会导致线程的优先级得不到体现。
而Convoy Formation则是说由于加锁,有可能在锁的后面有一条长长的,从sydney到wollongong的等待队伍。
《Non-blocking Synchronization》http://httpdyn.cs.huji.ac.il/moo ... ce/view.php?id=3416
  1. Unfortunately, these are not the only problems that lock-based code is faced with. In time-sliced systems, locks can lead to a very unhealthy coupling between synchronization and scheduling. If a thread is preempted, and – at the time when it is preempted – owns a lock, all other threads dependent on that lock are effectively blocked until the preempted thread finishes its operation and releases the lock. This remains true even when the preempted thread is of a low priority, and the blocked threads are of a higher priority. The result, in these cases, is known as priority inversion. Another phenomenon that may occur – perhaps even in combination with priority inversion – is that a large number of threads will queue up, waiting for the thread to release the desired lock. This phenomenon is known as convoy formation.
复制代码
回复  

使用道具 举报

您需要登录后才可以回帖 登录 | FreeOZ用户注册

本版积分规则

小黑屋|手机版|Archiver|FreeOZ论坛

GMT+10, 8-4-2025 04:02 , Processed in 0.028348 second(s), 17 queries , Gzip On, Redis On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表