If you look at GUI libraries in the .NET and Java platforms, you will find that these both require that interactions with the GUI are performed upon a single thread. This has become a hot topic lately, see Matthew Adams blog, and the related links.
So why is this implemented in this way?
This is a form of exclusion, enforced only by documentation (and the fact that you risk deadlocks if you ignore this).
Exclusion?
In a concurrent program multiple threads may attempt to access data elements at the same time. This can lead to a number of issues, referred to as race conditions. For example.
Consider the following pseudocode:
Thread 1:
- Read account value
- Increase value by $100
- Write back new account value
- Read account value
- Increase value by $50
- Write back new account value
Why?
The execution may occur in such as way that the result, after completion, does not result in the balance of the account increasing by $150. Imagine the following execution:
- Thread 1: Reads the account value as $1000 (the starting balance)
- Thread 1: Adds $100 to this, the result being $1100 is currently stored in a temporary variable.
- Thread 2: Reads the account value as $1000 ($1100 has not been stored yet!)
- Thread 2: Adds $50 to this, the result being stored in a temporary variable.
- Thread 2: Writes the value back into the account, the accounts balance is now $1050
- Thread 1: Writes the value stored in its temporary variable back into the account. The accounts balance is now $1100!
The issue then is, so how do you interact with the GUI? The answer is, with care and invoke. I will leave the details for you to read in the linked articles above.
No comments:
Post a Comment