C - pthread 函数重用 - 局部变量和竞争条件

标签 c multithreading pthreads race-condition critical-section

如果我定义了一个线程函数,它重用了主线程也使用的另一个函数……是否可能存在竞争条件?同一函数中的局部变量是否跨线程共享?在这种情况下,函数 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;
}    

最佳答案

。局部变量不跨线程共享。

关于C - pthread 函数重用 - 局部变量和竞争条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6760597/

相关文章:

c - 如何在 Pebble C API 中设置图层周围的线条边框?

c# - 如何使用 WPF 后台 worker

java - 为什么这段 java 代码中没有竞争条件?

c - pthread_cond_timedwait()

具有等待时间的 pthreads 的消费者/生产者

c - 如何在 Mac OSx 上处理来自外部程序的数据

线程可以在不锁定的情况下写入同一结构数组的不同元素吗?

c - 为什么这不会改变数组中的值?

multithreading - 列出当前进程中的所有线程?

android - 如何从 Android NDK 中的 pthread(C) 调用回调(JAVA)