gpt4 book ai didi

c - 函数的线程本地存储

转载 作者:行者123 更新时间:2023-11-30 15:42:02 26 4
gpt4 key购买 nike

我正在开发一个需要在多线程环境中执行队列操作的程序。我不确定函数的线程本地存储,而不仅仅是全局变量我试过了

__thread int head,tail;
__thread int q[MAX_NODES+2];

__thread void enqueue (int x) {
q[tail] = x;
tail++;
color[x] = GRAY;
}

__thread int dequeue () {
int x = q[head];
head++;
color[x] = BLACK;
return x;
}

我收到以下错误

fordp.c:71: error: function definition declared '__thread'

fordp.c:77: error: function definition declared '__thread'

我在某处读到一个函数已经是线程安全的,除非它使用共享变量,所以我尝试了

__thread int head,tail;
__thread int q[MAX_NODES+2];

void enqueue (int x) {
q[tail] = x;
tail++;
color[x] = GRAY;
}

int dequeue () {
int x = q[head];
head++;
color[x] = BLACK;
return x;
}

它确实编译没有错误,但我的执行结果是错误的,暗示队列在多线程平台上不能很好地工作。

有人可以解释一下这里发生了什么吗?

感谢任何帮助。

最佳答案

__thread 建议编译器为每个线程创建变量的实例。

我怀疑这就是您想要的队列,线程应该并发操作它的头部和尾部,因为一个线程所做的修改将被任何线程可见其他线程。

所以这里不要使用__thread,但要保护对全局变量的并发访问,例如使用一个或多个互斥体。

<小时/>

供您引用:http://en.wikipedia.org/wiki/Thread-local_storage

关于c - 函数的线程本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20354191/

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