I know that both threads can use the global variable k
and p
and also that after the CPU-time of one thread expired the other thread gets CPU-time and that's why I get different outputs like 9, 10 but I do not understand how the outputs 10 comes from. I guess it's because of the variable y
although I don't use it.
int k=2;
int* p;
void t1_f1(void){
int x=3;
p=&x;
sleep(1);
}
void t1_f2(void){
int y=5;
k++;
sleep(1);
}
void* t1_main(void* args){
t1_f1();
t1_f2();
return NULL;
}
void* t2_main(void* args){
sleep(1);
k=k* *p;
printf("%d \n", k);
return NULL;
}
int main(int argc, char ** argv){
pthread_t threads[2];
pthread_create(threads+1, NULL, t2_main, NULL);
pthread_create(threads, NULL, t1_main, NULL);
pthread_join(threads[0],NULL);
pthread_join(threads[1],NULL);
exit(0);
}
Your program has UB (Undefined Behavior
) and therefore you cannot expect any consistent output at all.
2 Examples for UB in your code:
t1_f1
you assign the global p
to the address of a local variable (x
). When x
goes out of the scope when the function returns, you'll have a dandling pointer, and dereferencing it (*p
) in t2_main
is UB.t2_main
might execute before p
is initialized at all (it is not initialized at the global scope where it is defined). In this case it's also UB to dereference it.sleep()
is not a threads synchronization call.