eat*_*mon 1 c multithreading pthreads critical-section race-condition
如果我定义一个重用主线程也使用的另一个函数的线程函数....是否可能存在竞争条件?是否在线程之间共享同一函数中的局部变量?在这种情况下,函数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;
}
Run Code Online (Sandbox Code Playgroud)