2014-07-01 143 views
1

我尝试在我的代码中添加一个节,它可以在取消情况下解锁互斥锁。这可能发生并会导致死锁。因此我试着添加pthread_cleanup_push(cleanup_unlock_mutex, &mutex_ftdi);,但是这行代码从我添加它直到代码文件结束的行中导致语法错误。如果我对代码行进行注释,那么程序将无误地编译。 我做错了什么?pthread_cleanup_push导致语法错误

void cleanup_unlock_mutex(void *p){ 
    pthread_mutex_unlock(p); 
} 

....... }else{ 
       for(unsigned count=0; count <= number_of_requests; count++){ 
        pthread_cleanup_push(cleanup_unlock_mutex, &mutex_ftdi); 
        pthread_mutex_lock(&mutex_ftdi); 
        process_requests(count, numberofthread); 
        pthread_mutex_unlock(&mutex_ftdi); 
       } 
      } // compiler error: error: expected ‘while’ before ‘}’ token 
.......... 

文件中的所有其他函数都会收到警告:ISO C禁止嵌套函数[-pedantic]。

+2

'}'错过。你可以首先缩进代码吗?奇怪!!!! 'else'没有'if'? 'while'循环在哪里?发布整个代码。 –

+0

没有别的奇怪,但我不想发布代码的if部分。代码完美。如果我添加'pthread_cleanup_push(cleanup_unlock_mutex,&mutex_ftdi)'这一行;'它不再可编译。如果评论这条线或删除它一切正常。但是我找不到任何错误,并且我不删除或添加任何''' –

+1

'但我不想发布代码的if部分.'如果你不想要任何人不想给你答案。 –

回答

4

您必须拨打pthread_cleanup_push()pthread_cleanup_pop()以匹配配对,并且您的代码段没有pthread_cleanup_pop()调用。

http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_cleanup_pop.html该文档解释了为什么:

这些功能可以作为宏来实现。申请书应当 确保它们出现的语句,并在同 词法范围内对(也就是pthread_cleanup_push()宏可能是 认为扩大到令牌列表的第一个符号是'{'pthread_cleanup_pop()扩展到令牌列表其最后一个标记是 对应'}')。

为了使这个具体的,一个可能的实现,从glibc的的nptl/sysdeps/pthread/pthread.h采取:

/* Install a cleanup handler: ROUTINE will be called with arguments ARG 
    when the thread is canceled or calls pthread_exit. ROUTINE will also 
    be called with arguments ARG when the matching pthread_cleanup_pop 
    is executed with non-zero EXECUTE argument. 

    pthread_cleanup_push and pthread_cleanup_pop are macros and must always 
    be used in matching pairs at the same nesting level of braces. */ 
# define pthread_cleanup_push(routine, arg) \ 
    do {          \ 
    __pthread_cleanup_class __clframe (routine, arg) 

/* Remove a cleanup handler installed by the matching pthread_cleanup_push. 
    If EXECUTE is non-zero, the handler function is called. */ 
# define pthread_cleanup_pop(execute) \ 
    __clframe.__setdoit (execute);      \ 
    } while (0)