[英]Threads and global variables: Why do I get 10 or 15 as output although i don't use the variable y?
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.我知道两个线程都可以使用全局变量
k
和p
,而且在一个线程的 CPU 时间到期后,另一个线程获得 CPU 时间,这就是为什么我得到不同的输出,如 9、10,但我不明白如何输出10来自。 I guess it's because of the variable y
although I don't use it.我想这是因为变量
y
虽然我不使用它。
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.您的程序具有UB (
Undefined Behavior
),因此您根本不能期望任何一致的 output。
2 Examples for UB in your code: 2 代码中 UB 的示例:
t1_f1
you assign the global p
to the address of a local variable ( x
).t1_f1
中,您将全局p
分配给局部变量 ( 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.x
离开 scope 时,您将有一个空指针,并且在t2_main
中取消引用它( *p
)是 UB。t2_main
might execute before p
is initialized at all (it is not initialized at the global scope where it is defined). t2_main
可能在p
完全初始化之前执行(它没有在定义它的全局 scope 处初始化)。 In this case it's also UB to dereference it.sleep()
is not a threads synchronization call.sleep()
不是线程同步调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.