2012-02-10 88 views
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任何想法?

回答

4

我相信你正在寻找术语Thread Local Storage。检查文档pthread_get_specific, pthread_get_specific,pthread_create_key或使用__thread storage class specifier

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

+0

+1 - 我已经远离pthreads太久了,我完全忘了它提供了作为lib的一部分。 – 2012-02-10 02:42:47

+0

谢谢! '__thread'似乎是更简单的方法。你是否应该为'struct'建议它? – 2012-02-10 02:53:35