线程中的私有变量

2023-12-09

我是一个开始使用pthreadsLinux 中用 C 语言。我需要创建和使用私有线程变量.

让我用一个例子来准确解释我需要什么。在下面的代码中,我创建了 4 个线程,我希望每个线程都创建一个私有变量foo,所以总共 4 个foo变量,每个线程一个。每个线程应该只“看到”它自己的foo变量而不是其他变量。例如,如果线程1 sets foo = 56然后调用doStuff, doStuff应该打印56。如果线程2 sets foo = 99然后调用doStuff, doStuff应该打印99。但如果线程1再次打电话doStuff, 56应重新打印。

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 */
}

关于如何做到这一点的任何想法(这基本上是私有线程变量的想法)使用pthreads?


我相信您正在寻找这个词线程本地存储。检查文档pthread_get_specific, pthread_get_specific, pthread_create_key或使用__thread 存储类说明符.

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

线程中的私有变量 的相关文章

随机推荐