gpt4 book ai didi

c - pthread_cleanup_push 导致语法错误

转载 作者:太空狗 更新时间:2023-10-29 15:52:16 25 4
gpt4 key购买 nike

我尝试在我的代码中添加一个部分,该部分能够在取消的情况下解锁互斥量。这可能会发生并会导致死锁。因此,我尝试添加 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
..........

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

最佳答案

您必须成对调用 pthread_cleanup_push()pthread_cleanup_pop(),并且您的代码片段没有 pthread_cleanup_pop() 调用.

文档位于 http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_cleanup_pop.html解释原因:

These functions may be implemented as macros. The application shall ensure that they appear as statements, and in pairs within the same lexical scope (that is, the pthread_cleanup_push() macro may be thought to expand to a token list whose first token is '{' with pthread_cleanup_pop() expanding to a token list whose last token is the corresponding '}' ).

为了具体化,一种可能的实现,取自 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)

关于c - pthread_cleanup_push 导致语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24503877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com