开发者

What happens if I return from a function without calling pthread_mutex_unlock?

Suppose I lock a mutex called wfg

pthread_mutex_lock(&wfg);
//and th开发者_JAVA技巧en I return from the function
return 0;

Would the mutex remain locked?


The mutex remains locked until pthread_mutex_unlock is called on it from the thread that obtained the lock. Functions have nothing to do with it. You could have something like

pthread_mutex_t wfg;
...
void razzle()
{
   pthread_mutex_lock(&wfg);
}

void dazzle()
{
  pthread_mutex_unlock(&wfg);
}

...
razzle();
... do stuff ...
dazzle();

And that would be fine (but silly).


Yes, it remains locked and the next person who tries to lock it will be unable to do so. Someone else (in the same thread) could subsequently unlock it somewhere else, but it is hard to verify the correctness of your program when aquisition and release are separated and consequently somewhat error prone. Valgrind includes a tool that might help tracking down problems like this and other, more subtle problems.

In C++ this is the perfect time to consider RAII

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜