Big Chemical Encyclopedia

Chemical substances, components, reactions, process design ...

Articles Figures Tables About

Pitfalls of Multi-Threading

Integer datum = 0 Create Thread 1 which computes Integer a = compute a() datum = datum + a Create Thread 2 which computes Integer b = compute b() datum = datum + b Wait for threads to complete [Pg.61]

Pseudocode iUustrating a race condition in a multi-threaded program. Two threads are created, each reading and modifying a datum at the same memory location, datu m. [Pg.61]

Thread 1 Thread 2 Thread 1 Thread 2 Thread 1 Thread 2 [Pg.62]

1 finishes execution before Thread 2 starts, and by the time Thread 2 reads datum, Thread 1 has completed its update to datum, and the expected result is obtained. In Case 2, both threads first read a copy of datum, perhaps loading its value into a register. Each thread then adds its result to this temporary copy and writes out the result, with Thread 2 writing out datum last. In this case. Thread 2 overwrites the contribution previously written out by Thread 1, and the result is incorrect. Case 3 is similar to Case 2, but when the datum is written out by the two threads, the order of the writes is reversed, and the datum written out lacks the contribution computed by Thread 2. The situation illustrated in Table 4.1 is called a race condition, and special precautions must be taken to avoid such cases. [Pg.62]

Process resources protected by A and B Unlock mutex B Unlock mutex A [Pg.63]


See other pages where Pitfalls of Multi-Threading is mentioned: [Pg.61]    [Pg.64]   


SEARCH



Multi-threading

Threading

© 2024 chempedia.info