Thread is an very effective way to improve program efficiency. However, thread is sometimes "risky" to use. One of most concern is modification toglobal variables.
Because threads could be running simultaneously and do not share stack information, global variable becomes a only way for communication between threads. However, when multiple threads modify same
global variable, result could be unexpected. This is one example
int a = 0
bar() {
a++;
if(a=1) {
print("Hello")
}
foo() {
a++
}
thread_create(&a)
thread_create(&b)
There will be three situations in this program:
1. Program go through thread bar(), a++ then a=1, then print Hello.
2. Program go through thread bar() in first "a++" then stop, switch to thread foo, and execute a++, then back to bar. This time a - 2 and program does not print Hello
3. Program go thread foo() first, exec a++ then go to bar(), exec a++. This time a = 2 and program does not print Hello.
So, this program just become unpredictable. Being unpredictable is dangerous in software design. So, Is there any way to prevent all disaster from happening?
Yes.
本文探讨了多线程环境下修改全局变量可能导致程序行为不可预测的问题,并通过一个具体示例展示了这种风险。当多个线程同时操作同一个全局变量时,可能会导致意外的结果。
3387

被折叠的 条评论
为什么被折叠?



