• 6678阅读
  • 3回复

[提问]请教关于QMutex的用法?? [复制链接]

上一主题 下一主题
离线starter
 
只看楼主 倒序阅读 楼主  发表于: 2012-10-23
关键词: 问题
如果有两个函数fun1,和fun2,分别在两个线程中调用,是不是必须在两个函数中同时加锁才有用,如果只在一个线程中加锁会怎么样?
比如: int d = 0;


QMutex mutex;


void fun1(int& d)
{
  mutex.lock();
  d += 5;
  d /= 4;
  mutex.unlock();
}

void fun2(int& d)
{
  mutex.lock(); //如果将此处注释掉会怎么样?
  d *= 2;
  d -= 2;
  mutex.unlock();//如果将此处注释掉会怎么样?
}
离线starter
只看该作者 1楼 发表于: 2012-10-23
难道就没有一个人能说说吗??
离线jdwx

只看该作者 2楼 发表于: 2012-10-23
回 1楼(starter) 的帖子
lock和unlock必须配对使用,如果没有unlock,这个mutex会被锁住,想要lock的其它线程就会卡住,一直等待mutex被unlock。
发帖时要说明:操作系统、Qt版本、编译器,这样能更快的得到回复。
离线ggkuroky
只看该作者 3楼 发表于: 2012-10-23
Locks the mutex. If another thread has locked the mutex then this call will block until that thread has unlocked it.
Calling this function multiple times on the same mutex from the same thread is allowed if this mutex is a recursive mutex. If this mutex is a non-recursive mutex, this function will dead-lock when the mutex is locked recursively


Unlocking a mutex that is not locked results in undefined behavior.
相信自己,天道酬勤!
快速回复
限100 字节
 
上一个 下一个