开发者

will goto violate mutexes?

开发者 https://www.devze.com 2023-02-14 14:45 出处:网络
I am doing it wrong, yes? ... if( you_think_youre_genius ) goto goto_sucks: ... pthread_mutex_lock(&mutex);

I am doing it wrong, yes?

...
if( you_think_youre_genius )
    goto goto_sucks:
...
pthread_mutex_lock(&mutex);

    do_stuff();

    goto_sucks:
        do_other_stuff()开发者_JS百科;

pthread_mutex_unlock(&mutex);


Yes, goto is direct jmp down at the binary code level so any function calls between the goto and the label will be skipped, period.


The mutex is acquired inside the pthread_mutex_lock function. If you jump past the function call, you will not have acquired the mutex. If you try to lock a mutex twice, you may deadlock. If you try to unlock a mutex you do not own, you may break things very badly.


If the condition is true, do_other_stuff will be called without the mutex being locked, and then the mutex will be released without locking it. Plain wrong!

Just without goto

if( you_think_youre_genius )  
    {  
         pthread_mutex_lock(&mutex);    
     }   
else  
{   
...     
pthread_mutex_lock(&mutex);   
//Assumming no expetion thrown   
do_stuff();   
}   
do_other_stuff();    
pthread_mutex_unlock(&mutex);   
0

精彩评论

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