Pthreads in C: Difference between revisions

From RoggeWiki
Jump to navigation Jump to search
(Created page with 'One very popular API for threading an application is pthreads, also known as POSIX threads, P1003.1c, or ISO/IEC 9945-1:1990c. ====Data race==== THREAD 1 THREAD …')
(No difference)

Revision as of 18:27, 17 December 2011

One very popular API for threading an application is pthreads, also known as POSIX threads, P1003.1c, or ISO/IEC 9945-1:1990c.

Data race

THREAD 1                THREAD 2
a = data;               b = data;
a++;                    b--;
data = a;               data = b;

Now if this code is executed serially (THREAD 1, the THREAD 2) there isn't a problem. However threads execute in an arbitrary order, so consider this:

THREAD 1                THREAD 2
a = data;
                       b = data;
a++;
                       b--;
data = a;
                       data = b;
[data = data - 1!!!!!!!]

So data could end up +1, 0, -1, and there is NO way to know which as it is completely non-deterministic!

In fact the problem is worse, because on many machines a = data is non-atomic. This means that when data is loaded into a, you could end up with the low order bits of the old data, and the high order bits of the new data. CHAOS.

The solution to this is to provide functions that will block a thread if another thread is accessing data that it is using.

Pthreads use a data type called a mutex to achieve this.