gpt4 book ai didi

c - 如何防止重新初始化 pthread_rwlock_t

转载 作者:太空宇宙 更新时间:2023-11-04 08:33:59 25 4
gpt4 key购买 nike

我正在声明 pthread_rwlock_t 静态全局数组。例如静态 pthread_rwlock_t cm[255];在构造函数内部,我想初始化 255 个互斥量之一(我用静态计数器跟踪)

现在我很困惑1)我不想再次重新初始化锁,那很糟糕!我认为重新初始化应该返回一些错误代码,但它没有:

#include<stdio.h>
#include <pthread.h>

static pthread_rwlock_t cm[2];

int main()
{
int ret;
ret = pthread_rwlock_init(&cm[0], NULL);
ret = pthread_rwlock_wrlock(&cm[0]);
printf("Ret: %d\n", ret);

ret = pthread_rwlock_init(&cm[0], NULL);
printf("Ret: %d\n", ret);

ret = pthread_rwlock_wrlock(&cm[0]);
printf("Ret: %d\n", ret);
}

结果:

Ret: 0
Ret: 0
Ret: 0

任何人都可以帮忙,1)如果这是可能的,那么如何? 2) 如果不是,应该采用什么替代方法?

编辑 1:我正在根据收到的评论/答案进行更新:

Instead, just put the rwlocks inside the objects they protect. So I have n # of objects getting called, and will be using that many pthread_lock .. so disadvantage is memory. Hence I'm trying to improve on that part with global array of locks. Picking 256 to get good distribution.

最佳答案

在同一个对象上多次调用 pthread_rwlock_init(或类似的任何 pthread 原语初始化函数)是未定义的行为,并且从逻辑上讲,这样做是没有意义的,因为(正如您所展示的那样)该对象已在使用中。您在 2501 的回答的评论中说您不能使用 pthread_once,但这没有任何意义。如果您能够调用 pthread_rwlock_init,则可以使用执行对 pthread_rwlock_init 的调用的 init 函数来调用 pthread_once

但是我真的认为您遇到了 XY problem .维护一个 rwlocks 的“全局池”并在构造函数中动态分发它们是没有意义的。相反,只需将 rwlocks 放在它们保护的对象中。如果你真的想像你正在做的那样从全局池中分发它们,你需要跟踪哪些已经分发了独立初始化它们的工作,并有任务在获得一个后初始化它们,并在将其返回池之前销毁一个,由使用它们的对象的构造函数/析构函数处理。

关于c - 如何防止重新初始化 pthread_rwlock_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27071631/

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