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.