Tuesday, April 8, 2008

[Programming] Threads (4) - synchronization

Threads (4) - synchronization

Previously we described the issue of joinable and detached thread scheduling. In practice, the situation is not that simple. Most of the threaded programs are concurrent programs, which means the operating system will run multiple threads at the same time. However, there's no way to know when a thread will be scheduled to run by the system. The order of thread's running is not deterministic.

Another big problem of threaded programming is that, unlike processes, threads share the same address space. This is one of the powerful aspects of threads - if one thread changes the value of a variable, other threads will see this modification subsequently. However, this sharing could also be dangerous without careful design and implemenation.

The third thing is that debugging a threaded program is not easy as debugging a single-thread program - you may not reproduce the same result in a multi-threaded program.

Therefore, the synchronization among threads is a very important issue. In order to understand the details of synchronization, let's first learn some new concepts one by one: critical section, atomic operation, race condition, mutex, semaphore, deadlock.

Critical section: it means a resource (usually implemented by a sequence of code) that should be exclusively used by a program for a period of its execution. In simple words, if a thread begins executing a critical section code, it must continue to the end without being canceled.

Race condition: since a critical section can only be exclusively used, when multi threads occur concurrently, they will compete for the critical section. In this situation, we say there is a race condition.

In order to eliminate race conditions and ensure a critical section being implemented successfully, we need a way to make operations atomic, which is described below.

Atomic operation: when we speak of an atomy, we usually mean that it is a tiny particle indivisible. So here the atomic operation has the similar meaning: once the operation starts, it will not be canceled, pasued or interrupted until it completes; at the meantime, no other operation will take place either.In multi-threaded programming, the operating system will provide and guarantee some operations to be atomic.

(to be continued)

1 comment:

Anonymous said...

[URL=http://gfdrunk.info/young-lesbian-17/young-litle-girls-nude.html]young litle girls nude[/URL]