c - 线程中的私有(private)变量

标签 c multithreading pthreads multicore

我是在 Linux 中将 pthreads 与 C 结合使用的初学者。我需要创建和使用私有(private)线程变量

让我用一个例子来准确解释我需要什么。在下面的代码中,我创建了 4 个线程,我希望每个线程都创建一个私有(private)变量 foo,因此总共有 4 个 foo 变量,每个线程一个。每个线程应该只“看到”它自己的 foo 变量,而不是其他的。例如,如果线程 1 设置 foo = 56 然后调用 doStuffdoStuff 应该打印 56 。如果线程 2 设置 foo = 99 然后调用 doStuffdoStuff 应该打印 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 执行此操作(这基本上是私有(private)线程变量的想法)有什么想法吗?

最佳答案

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

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

关于c - 线程中的私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9221939/

相关文章:

ios - 在 posix 线程上创建自动释放池

c - 指向结构的指针数组

java - Volatile 关键字线程安全

java - 避免多个对象事务死锁的最佳方法?

python - 如何在python中实现线程socket.recv()?

c - 无法设置 Pthread 优先级

c++ - 哪些 C++ 标准库头调用了 GCC 的 -pthread 选项要求?

c++ - GTK+ 与任何程序

c++ - 有时我的窗口句柄好,有时坏

c - 为什么设置 AI_PASSIVE 时 getaddrinfo() 返回第一个 IPv4 而不是 IPv6?