如何访问主线程中定义的变量?

时间:2014-01-20 08:35:20

标签: c pthreads

我有一个程序。在main()中,它创建了两个线程thread_A和thread_B。

int main(int argc, char **argv)
{
        pthread_t thread_A, thread_B;
        volatile int label; // share with thread_A and thread_B

        pthread_create(&thread_A, NULL, thread_A_Main, NULL);
        pthread_create(&thread_B, NULL, thread_B_Main, NULL);

        // other codes ...
}

thread_A_Mainthread_B_Main位于其他文件中。现在我想访问thread_A和thread_B中的label,下面的方法不起作用:

extern volatile int label;
void *thread_A_Main(void *) 
{
    // some codes ...
    label++;
    // some other codes ...
}

编译时,我被告知thread_a_main.c:(.text+0x1ce): undefined reference to label。 在主线程和其他创建的线程之间共享变量的正确方法是什么?

3 个答案:

答案 0 :(得分:2)

你应该通过声明之外的来使它成为全局的。

volatile int g_label; // global

int main() {
    // ...
}

当您将label 放在main()内时,该变量是 local main,这通常意味着它存在于main(临时存储)的堆栈中。

通过将其移到外面,我们将它放在数据部分中,该部分与实际程序文本一起存储在整个过程可访问的内存区域中。

答案 1 :(得分:2)

  1. 在源文件中声明它为非静态全局变量(不在头文件中)。

  2. “Extern”在任何您想要使用它的地方,或者只是在一个头文件中,然后包含此文件。

  3. 您可能必须将其视为关键部分并使用某些OS资源(互斥锁,信号量等)保护它,以确保不同线程对此变量的互斥访问。

答案 2 :(得分:0)

你的案例中的

标签存储在主线程堆栈中,这意味着它在你的其他线程中是不可访问的。 您可以尝试将标签设为全局。