當我用相同的函數創建兩個線程時,函數中的靜態變量是共享的嗎?他們在哪裏得救?因爲如果它們保存在主線程的靜態數據中,它們將被共享給兩個線程。線程的相互作用
代碼例如:
void fill_g_msg(void){
pthread_t t1, t2;
pthread_create(&t1, NULL, thread_fill, 「first");
pthread_create(&t2, NULL, thread_fill, 「second");
// wait for both threads to finish
pthread_join(t1, NULL);
pthread_join(t2, NULL);
}
void* thread_fill(void *arg){
int a;
if(strcmp((char*)arg, 「second」) == 0) {
a = 1;
} else {
a = 2;
}
return null;
}
您的例子似乎沒有任何靜態變量。 –
我的意思是「a」變量 ,它是靜態的嗎? – Moawiya
不,每次函數調用都會得到自己的一組局部變量,除非明確地添加一個'static'。 –