保持pthread的局部变量 [英] Keep pthread variables local

查看:273
本文介绍了保持pthread的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法,而使用 pthreads.h中在Linux GCC,以保持局部变量线程功能:

Is there a way while using pthread.h on a Linux GCC to keep variables local to the thread-function:

int i = 42; // global instance of i    

int main() {
    pthread_t threads[2];
    long t;
    pthread_create(&threads[t], NULL, ThreadFunction, (void *) t;
    pthread_create(&threads[t], NULL, ThreadFunction2, (void *) t;
}

我不知道是否有在POSIX函数的参数创建新的线程,并保持局部变量:

I wonder whether there is a parameter at the POSIX function creating the new thread and keeping the variables local:

void *ThreadFunction(void *threadid)
{
    int i=0;
    i++; // this is a local instance of i
    printf("i is %d", i); // as expected: 1
}

void *ThreadFunction2(void *threadid)
{
    i += 3; // another local instance -> problem
}

在哪里事后 I 为42即使我已经定义了一个 I previously我想这个 I 不要被我的线程中。

Where afterwards i is 42. Even if I have defined an i previously I want this i not to be within my threads.

推荐答案

全局变量总是在整个编译单元提供(甚至更多编译单元,如果您使用外部声明)。这有没有关系线程,它的C / C ++的默认行为++。推荐的解决方案是不使用全局 - 全局是邪恶的。如果你仍然需要使用全局变量,你可能需要preFIX他们,如 g_i 。另一种解决方案是把你的线程函数到另一个编译单元(C文件)。

Global variables are always available in the whole compilation unit (or even more compilation units if you use external declarations). This has nothing to do with threads, it's the default behavior of C/C++. The recommended solution is not to use globals - globals are evil. If you still need to use globals, you may want to prefix them, such as g_i. Another solution is to put your thread functions into another compilation unit (c file).

这篇关于保持pthread的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆