Search code examples
cmultithreadingpthreadsrace-conditioncritical-section

C - pthread function reuse - local variables and race conditions


If I define a thread function that reuses another function that the main thread also uses....is it possible that there can be a race condition? Are the local variables in the same function shared across threads? In this case the function do_work is used in both the thread_one thread and the main thread. Can the local variable x in the function do_work be modified by both threads so it creates an unexpected result?

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;
}    

Solution

  • No. Local variables aren't shared across threads.