是否存在,而在Linux GCC使用pthread.h
保持局部變量線程功能的方法:保持並行線程局部變量
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函數中的參數創建新的線程並保持局部變量:
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
以前我想這i
不要被我的線程中。
你的問題是什麼?代碼中的所有'i's都是局部變量。結果42證實了這一點。 – 2010-11-07 18:04:03
恩,這個例子很糟糕...我明白了。我想我在線程1是1,在線程2是3,並保持那樣...必須編輯。 – wishi 2010-11-07 18:09:07
@Duck:你可以修改哪些代碼?簡單的解決方案是在本地聲明第二個'i'。 – kennytm 2010-11-07 18:18:11