wis*_*shi 2 c linux posix pthreads
有没有办法在pthread.hLinux 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;
}
Run Code Online (Sandbox Code Playgroud)
我想知道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
}
Run Code Online (Sandbox Code Playgroud)
之后i是42岁.即使我之前已经定义了i一个,我希望这i不在我的线程之内.
在gcc中,您可以使用说明__thread符创建一个全局变量thread-local :
__thread int i = 42;
Run Code Online (Sandbox Code Playgroud)
不要那样做.根据您的需要,有更好的解决方案.