pthread_once和互斥锁
以下代码由多个线程执行pthread_once和互斥锁,c,multithreading,C,Multithreading,以下代码由多个线程执行 alloc_global_ctx() { if (global ctx is not allocated) { global ctx = calloc(1, sizeof(global ctx)); } return global ctx; } once_routine() { …. alloc_global_ctx() …. } init_routine() { Take init_mutex; Call pth
alloc_global_ctx()
{
if (global ctx is not allocated) {
global ctx = calloc(1, sizeof(global ctx));
}
return global ctx;
}
once_routine()
{
….
alloc_global_ctx()
….
}
init_routine()
{
Take init_mutex;
Call pthread_once(once_variable, once_routine);
alloc_global_ctx();
….
Release init_mutex;
}
当我的程序执行
init_例程
时(两个线程调用init_例程
),我希望全局ctx
将由执行一次例程
的线程分配。然而,从调试日志中,我发现大多数情况下,运行once\u例程的线程和分配全局变量的线程是不同的。这是预期的吗?当一个线程执行一次pthread\u
时,它是否会释放init\u互斥锁?您需要发布一个完整的示例。您的代码无法编译和运行,因此我们无法看到您所看到的内容。pthread_曾经不知道您的init_互斥体,因此发生了其他事情-无法从此处发布的伪代码中读取。但是,由于您已经使用互斥体保护该区域,因此不需要pthread_once调用,或者您可以摆脱互斥体,只依赖pthread_once。如何定义“once_变量”?