Cra*_*enz 25 multithreading mutex
如果解锁已解锁的互斥锁,行为是不安全,安全还是未定义?
问题的目的与下面的代码有关,我不知道在if块中解锁互斥锁是否更好,或者只是在if块之外.
// This chunk of code makes dual locking semi-autonomous.
int c_lckd = 0, q_lckd = 0;
if (pthread_mutex_trylock(&crunch_mutex) == 0) c_lckd = 1;
if (pthread_mutex_trylock(&queue_mutex) == 0) q_lckd = 1;
if (q_lckd && !c_lckd) { QUEUE_UNLOCK; q_lckd = 0; }
else if (c_lckd && !q_lckd) { CRUNCH_UNLOCK; c_lckd = 0; }
if (c_lckd && q_lckd) {
printf("cr = %d, max = %d, cnt = %d\n",
crunching, max_crunching, queue_count(conn_queue));
if (crunching < max_crunching && queue_count(conn_queue)) {
pthread_t tid =
pthread_create(
&tid,
NULL,
crunch_conn,
(void *)queue_dequeue(conn_queue)
);
crunching++;
}
CRUNCH_UNLOCK QUEUE_UNLOCK
}
Run Code Online (Sandbox Code Playgroud)
谢谢,陈兹
Gle*_*len 23
对于pthreads,它将导致未定义的行为.从pthread_mutex_unlock的手册页:
使用调用线程未保留的互斥锁调用pthread_mutex_unlock()将导致未定义的行为.
其他互斥体将有自己的行为.正如其他人所说,最好阅读手册,了解您使用的互斥锁.
正如Glen指出的那样,如果您尝试解锁未锁定的互斥锁,则会出现未定义的行为- 请勿尝试.调试线程很难,也不会调用未定义的行为.
更重要的是,编码风格有点不寻常 - 因为除非你同时获得两个锁,否则你不会做任何事情,因此代码如下:
if (pthread_mutex_trylock(&crunch_mutex) == 0)
{
if (pthread_mutex_trylock(&queue_mutex) == 0)
{
printf("cr = %d, max = %d, cnt = %d\n",
crunching, max_crunching, queue_count(conn_queue));
if (crunching < max_crunching && queue_count(conn_queue))
{
pthread_t tid;
int rc = pthread_create(&tid, NULL,
crunch_conn, (void *)queue_dequeue(conn_queue));
if (rc != 0)
{
// Error recovery
// Did you need what was returned by queue_dequeue()
// to requeue it, perhaps?
}
else
{
crunching++;
// Do something with tid here?
}
}
QUEUE_UNLOCK;
}
CRUNCH_UNLOCK;
}
Run Code Online (Sandbox Code Playgroud)
这避免了'我做了'变量; 很明显,只要解锁宏执行预期的操作(并且没有杂散异常或setjmps),锁定的互斥锁就会被解锁.当crunch互斥锁不可用时,它还可以避免在锁定队列互斥锁时浪费能量 - 但与增加的清晰度相比,这是一个小问题.
| 归档时间: |
|
| 查看次数: |
23173 次 |
| 最近记录: |