Chinaunix

标题: pthread_mutex_unlock失败的问题 [打印本页]

作者: 729926317    时间: 2011-05-07 21:41
标题: pthread_mutex_unlock失败的问题
本帖最后由 729926317 于 2011-05-07 22:15 编辑

最近在学POSIX,有些地方不理解
还望大家帮帮忙
谢了~

unlock失败我上网找了下应该是在当前线程不拥有锁的情况下会失败。
然后我这段代码那个“Fail”怎么都打印不出来,不知道什么。
  1. #include <pthread.h>
  2. #include <time.h>
  3. #include <unistd.h>
  4. #include <errno.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>


  7. typedef struct my_struct_tag {
  8.     pthread_mutex_t     mutex;  /* Protects access to value */
  9.     int                 value;  /* Access protected by mutex */
  10. } my_struct_t;

  11. my_struct_t data = {
  12.     PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0};


  13. void *wait_thread (void *arg)
  14. {
  15.     int status;
  16.     status = pthread_mutex_lock (&data.mutex);
  17.     sleep (5);//等待5秒,让另一个线程解锁互斥量,来造成解锁失败
  18.     status = pthread_mutex_unlock (&data.mutex);
  19.     return NULL;
  20. }

  21. int main (int argc, char *argv[])
  22. {
  23.     int status;
  24.     pthread_t wait_thread_id;
  25.     struct timespec timeout;

  26.     status = pthread_create (&wait_thread_id, NULL, wait_thread, NULL);
  27.     sleep(1);//等待1秒,让其他线程锁住互斥量
  28.     status = pthread_mutex_unlock (&data.mutex);
  29.     printf("%d\n",status);
  30.     if(status!=0)
  31.     {
  32.         printf("Fail\n");
  33.     }

  34.     return 0;
  35. }
复制代码
status输出显示是0
解锁成功?!。。。不可能啊
作者: peidright    时间: 2011-05-07 22:08
“unlock失败我上网找了下应该是在当前线程不拥有锁的情况下会失败”这个是错的.
posix,我也不知道。。
作者: crazyhadoop    时间: 2011-05-07 22:09
本帖最后由 crazyhadoop 于 2011-05-07 22:16 编辑

sleep(1);//等待1秒,让其他线程锁住互斥量  你确定其它进程可以来解锁?

status = pthread_mutex_unlock (&data.mutex); 你能确定是哪个 unlock出错了吗?
这个不对称必然有错


www.crazyhadoop.com
作者: 729926317    时间: 2011-05-07 22:16
回复 2# peidright

http://www.mkssoftware.com/docs/man3/pthread_mutex_unlock.3.asp

这上面是这个意思。起码在当前线程不拥有互斥量的时候,解锁是会失败的。
作者: 729926317    时间: 2011-05-07 22:22
回复 3# crazyhadoop

我让另一个线程sleep 5秒就是为了让main的这个线程来解锁。

而在不拥有该互斥量的时候,线程对该互斥量的解锁是会失败的 http://www.mkssoftware.com/docs/man3/pthread_mutex_unlock.3.asp

我就是想捕捉到这个失败
作者: peidright    时间: 2011-05-07 22:33
If the mutex type is PTHREAD_MUTEX_NORMAL, error detection is not provided. If a thread attempts to unlock a mutex that is has not locked or a mutex which is unlocked, undefined behavior results.
作者: 729926317    时间: 2011-05-08 12:16
回复 6# peidright


我在create线程之后买了线程sleep了1秒就是让刚刚创建的线程来锁住mutex
然后用main线程去解锁

这个时候这个互斥量应该已经被创建的锁住了
作者: shimmey    时间: 2011-05-08 18:10
代码編譯通不過
tt.c:41: warning: braces around scalar initializer
tt.c:41: warning: (near initialization for ‘data.value’)
環境:
gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5)
作者: macroideal    时间: 2011-05-08 20:25
晕...失败才是正确的,你成功了才怪呢
作者: JohnBull    时间: 2011-05-08 23:42
6楼正解
作者: 729926317    时间: 2011-05-09 19:11
回复 7# 729926317

算是理解了,谢谢




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2