【问题标题】:Private Variables in Threads线程中的私有变量
【发布时间】:2012-03-02 13:51:37
【问题描述】:

我是在 Linux 中将 pthreads 与 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 */
}

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

【问题讨论】:

    标签: c multithreading pthreads multicore


    【解决方案1】:

    我相信您正在寻找术语Thread Local Storage。查看pthread_get_specific, pthread_get_specificpthread_create_key 的文档或使用__thread storage class specifier

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

    【讨论】:

    • +1 - 我离开 pthread 太久了,我完全忘记了它作为 lib 的一部分提供的。
    • 谢谢! __thread 似乎是更简单的方法。你也应该为structs 推荐它吗?
    猜你喜欢
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多