我尝试在我的代码中添加一个部分,它可以在取消的情况下解锁互斥锁.这可能会发生并导致死锁.因此我尝试添加,pthread_cleanup_push(cleanup_unlock_mutex, &mutex_ftdi);但这行导致语法错误从我添加它直到代码文件的末尾的行.如果我评论代码行,程序将编译没有任何错误.我做错了什么?
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
..........
Run Code Online (Sandbox Code Playgroud)
文件中的所有其他函数都会收到警告:ISO C禁止嵌套函数[-pedantic].
Mic*_*urr 10
您必须呼叫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)
Run Code Online (Sandbox Code Playgroud)