使用时有没有办法pthread.h
在 Linux GCC 上将变量保留为线程函数的本地变量:
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;
不要那样做。有更好的解决方案,具体取决于您想要做什么。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)