gpt4 book ai didi

c - 将 pthread 变量保留在本地

转载 作者:太空狗 更新时间:2023-10-29 11:24:56 25 4
gpt4 key购买 nike

在 Linux GCC 上使用 pthread.h 时有没有办法将变量保持在线程函数的本地:

int i = 42; // global instance of i    

int main() {
pthread_t threads[2];
long t;
pthread_create(&threads[t], NULL, ThreadFunction, (void *) t;
pthread_create(&threads[t], NULL, ThreadFunction2, (void *) t;
}

我想知道在 POSIX 函数中是否有一个参数创建新线程并将变量保持在本地:

void *ThreadFunction(void *threadid)
{
int i=0;
i++; // this is a local instance of i
printf("i is %d", i); // as expected: 1
}

void *ThreadFunction2(void *threadid)
{
i += 3; // another local instance -> problem
}

之后 i 是 42。即使我之前定义了一个 i,我也不希望这个 i 在我的线程中。

最佳答案

在 gcc 中,您可以使用 __thread 说明符使全局变量成为线程局部变量:

__thread int i = 42;

不要那样做。有更好的解决方案,这取决于你想做什么。

关于c - 将 pthread 变量保留在本地,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4118943/

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