Thursday, January 20, 2005

Interacting with a GUI

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:

  1. Read account value
  2. Increase value by $100
  3. Write back new account value
Thread 2:
  1. Read account value
  2. Increase value by $50
  3. Write back new account value
In a sequential (single threaded) programs there would be no issues with this type of code... However, if these two threads run concurrently then we have an issue.

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:

  1. Thread 1: Reads the account value as $1000 (the starting balance)
  2. Thread 1: Adds $100 to this, the result being $1100 is currently stored in a temporary variable.
  3. Thread 2: Reads the account value as $1000 ($1100 has not been stored yet!)
  4. Thread 2: Adds $50 to this, the result being stored in a temporary variable.
  5. Thread 2: Writes the value back into the account, the accounts balance is now $1050
  6. Thread 1: Writes the value stored in its temporary variable back into the account. The accounts balance is now $1100!
There are several ways to get around this issue, one such approach is called exclusion. Using this approach, you ensure that only one thread at a time can manipulate the shared data. Exclusion can be implemented via critical section, locks that allow only a single thread to enter the critical section of code. With the GUIs, the exclusion is by protocol. In essence, the documentation indicates that, while they don't stop it, you are not allowed to access these items from other threads.

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: