如果我定義了重用主線程也使用的另一個函數的線程函數....是否有可能存在競爭條件?跨線程共享同一個函數中的局部變量嗎?在這種情況下,函數do_work用於thread_one線程和主線程。兩個線程是否可以修改函數do_work中的局部變量x,以便創建意想不到的結果?C - pthread函數重用 - 局部變量和競爭條件
void *thread_one() {
int x = 0;
int result;
while(1) {
for(x=0; x<10; x++) {
result = do_work(x);
}
printf("THREAD: result: %i\n", result);
}
}
int do_work(int x) {
x = x + 5;
return x;
}
int main(int argc, char**argv) {
pthread_t the_thread;
if((rc1 = pthread_create(&the_thread, NULL, thread_one, NULL))) {
printf("failed to create thread %i\n", rc1);
exit(1);
}
int i = 0;
int result = 0;
while(1) {
for(i=0; i<12; i+=2) {
result = do_work(i);
}
printf("MAIN: result %i\n", result);
}
return 0;
}
但請記住,本地*靜態*變量是共享的,因此可能需要同步才能安全地訪問它們。 –