【发布时间】:2012-03-02 13:51:37
【问题描述】:
我是在 Linux 中将 pthreads 与 C 一起使用的初学者。我需要创建和使用私有线程变量。
让我用一个例子来准确解释我需要什么。在下面的代码中,我创建了 4 个线程,我希望每个线程都创建一个私有变量 foo,因此总共有 4 个 foo 变量,每个线程一个。每个线程应该只“看到”它自己的foo 变量而不是其他线程。例如,如果线程1 设置foo = 56 然后调用doStuff,doStuff 应该打印56。如果线程2 设置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 执行此操作的任何想法(基本上是私有线程变量的想法)?
【问题讨论】:
标签: c multithreading pthreads multicore