如果我定义了一个线程函数,它重用了主线程也使用的另一个函数......是否可能存在竞争条件?同一函数中的局部变量是否跨线程共享?在这种情况下,函数 do_work 用于 thread_one 线程和主线程。两个线程都可以修改函数 do_work 中的局部变量 x 从而产生意想不到的结果吗?
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;
}