2
我是在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
任何想法?
+1 - 我已经远离pthreads太久了,我完全忘了它提供了作为lib的一部分。 – 2012-02-10 02:42:47
谢谢! '__thread'似乎是更简单的方法。你是否应该为'struct'建议它? – 2012-02-10 02:53:35