线程中的私有变量

Foo*_* R. 2 c multithreading multicore pthreads

我是pthreadsLinux上C语言的入门者。我需要创建和使用私有线程变量

让我用一个例子确切地解释我所需要的。在下面的代码中,我创建了4个线程,我希望它们每个都创建一个私有变量foo,因此总共有4个foo变量,每个线程一个。每个线程应仅“看到”它自己的foo变量,而不是其他变量。例如,如果线程1设置foo = 56然后调用doStuffdoStuff则应打印56。如果线程2设置foo = 99然后调用doStuffdoStuff则应打印99。但是如果线程1再次调用doStuff56应该重新打印。

void doStuff()
{
  printf("%d\n", foo); // foo is different depending on each thread
}

void *initThread(void *threadid)
{
  // initalize private thread variable (foo) for this thread
  int foo = something;

  printf("Hello World! It's me, thread #%ld!, %d\n", (long) threadid, x);
  doStuff();
}

int main()
{
   pthread_t threads[4];

   long t;
   for (t = 0; t < 4; t++){
     printf("In main: creating thread %ld\n", t);
     pthread_create(&threads[t], NULL, initThread, (void *) t);
   }

   pthread_exit(NULL); /* support alive threads until they are done */
}
Run Code Online (Sandbox Code Playgroud)

关于如何执行此操作的任何想法(基本上是私有线程变量的想法)pthreads

And*_*ker 5

我相信您正在寻找Thread Local Storage一词。查看文档中有关pthread_get_specific,pthread_get_specificpthread_create_key的信息,或使用__thread存储类说明符

另一种选择是使用单个全局变量并使用互斥锁,或者简单地将foo作为参数传递。