Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

will goto violate mutexes?

Tags:

c

mutex

goto

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();

pthread_mutex_unlock(&mutex);
like image 470
palindrom Avatar asked Mar 04 '11 07:03

palindrom


3 Answers

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.

like image 89
Andrew White Avatar answered Oct 10 '22 12:10

Andrew White


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.

like image 39
rlibby Avatar answered Oct 10 '22 13:10

rlibby


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);   
like image 45
Manoj R Avatar answered Oct 10 '22 14:10

Manoj R