Reputation: 3208
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;
}
Upvotes: 1
Views: 2751
Reputation: 19241
No, local variables of thread are not shared accross threads.
In detail, each thread has its own set of registers and stack. However, code and global data are shared.
Upvotes: 3
Reputation: 215241
No, and the more important point is that local (automatic) variables are not shared between multiple instances of a function even in the same thread. This is how recursion works and what makes it possible for functions to be reentrant.
Upvotes: 1
Reputation: 10865
No since x
is a local variable. Every thread works with his own x
variable, so there's no possibility for a thread to modify other thread's x
.
Upvotes: 1