免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
123456
最近访问板块 发新帖
楼主: 埋头苦编
打印 上一主题 下一主题

请高手解释下程序运行过程:多线程加锁阻塞问题 [复制链接]

论坛徽章:
0
51 [报告]
发表于 2011-11-24 10:07 |只看该作者
本帖最后由 digdeep126 于 2011-11-24 10:09 编辑

回复 49# 埋头苦编
关键是锁,不是这样使用的!
不能这样使用:pthread_mutex_unlock(mut+next((int)ptr));

论坛徽章:
0
52 [报告]
发表于 2011-11-24 10:13 |只看该作者
http://biancheng.dnbcw.info/linux/259179.html
3.解锁
   解锁必须满足
      (1)互斥锁处于加锁状态
      (2)只能由加锁的线程解锁(谁加谁解);
   解锁后等待队列中的第一个线程获得互斥锁.
       int pthread_mutex_unlock(pthread_mutex_t *mutex);

论坛徽章:
0
53 [报告]
发表于 2011-11-25 09:50 |只看该作者
这个输出跟sleep应该没什么关系。线程之间竞争CPU,没有特定的执行顺序。每个线程若同时释放了它自己的下一个锁,那么下一次的输出也将由竞争到cpu的那个线程执行。

论坛徽章:
0
54 [报告]
发表于 2011-11-25 10:22 |只看该作者
回复 52# digdeep126

不能说谁加谁解,那篇文章也不严谨,一般用法是谁加谁解,但:
如果指定的互斥对象在以下情况下由调用的互斥对象拥有,那么 pthread_mutex_unlock 子例程将指定的互斥对象重新设置为已解锁状态:

    * 如果互斥对象已经被解锁,子例程返回错误。
    * 如果互斥对象为调用线程所拥有,子例程解锁互斥对象。
    * 如果互斥对象为另一个线程所拥有,子例程可能返回错误或者解锁互斥对象,这取决于互斥的类型。建议不要解锁互斥对象,因为互斥对象通常被同一个 pthread 锁定和解锁。
    来自http://publib.boulder.ibm.com/in ... progc%2Fmutexes.htm

论坛徽章:
0
55 [报告]
发表于 2011-11-25 13:37 |只看该作者
本帖最后由 digdeep126 于 2011-11-25 13:53 编辑

回复 54# 埋头苦编
你的翻译,我实在看不明白,还是看原文吧:
http://publib.boulder.ibm.com/in ... progc%2Fmutexes.htm

The thread that locked a mutex is often called the owner of the mutex.

The pthread_mutex_unlock subroutine resets the specified mutex to the unlocked state if it is owned by the calling mutex under the following conditions:

If the mutex was already unlocked, the subroutine returns an error.
If the mutex was owned by the calling thread, the subroutine unlocks the mutex.
If the mutex was owned by another thread, the subroutine might return an error or unlock the mutex depending on the type of mutex. Unlocking the mutex is not recommended because mutexes are usually locked and unlocked by the same pthread.

既然:Unlocking the mutex is not recommended
那么推荐的方式就是: 对pthread_mutex_unlock函数的调用,不应该解锁“非自己线程拥有的锁”。
那我们在往前推一步:既然pthread_mutex_unlock函数不应该解锁“非自己线程拥有的锁”,那么“自己线程拥有的锁”就只能是拥有锁的线程自己调用pthread_mutex_unock来解锁了,也就是说“推荐的方式是:谁加锁,谁解锁。”
另:“The pthread_mutex_unlock subroutine resets the specified mutex to the unlocked state if it is owned by the calling mutex under the following conditions:”这一句英文中的:calling mutex似乎应该为 calling thread (仅仅是自己的猜测!)

论坛徽章:
0
56 [报告]
发表于 2011-11-25 14:41 |只看该作者
前排前排

论坛徽章:
0
57 [报告]
发表于 2011-11-28 15:01 |只看该作者
回复 55# digdeep126
那段话我当时看也有点别扭,有句话太长了(翻译的太英文化了),不过仔细看还是懂了,两端话其实意思是差不多的了,呵呵。现在可以确定的是:默认类型的锁可以由别的线程打开(否则我的程序是跑不动的),但真正写代码时是不这么用的。有劳你了,哈哈,同僚
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP