"thread safe programming" Code Answer


thread-safety is one aspect of a larger set of issues under the general heading of "concurrent programming". i'd suggest reading around that subject.

your assumption that two threads cannot access the struct at the same time is not good. first: today we have multi-core machines, so two threads can be running at exactly the same time. second: even on a single core machine the slices of time given to any other thread are unpredicatable. you have to anticipate that ant any arbitrary time the "other" thread might be processing. see my "window of opportunity" example below.

the concept of thread-safety is exactly to answer the question "is this dangerous in any way". the key question is whether it's possible for code running in one thread to get an inconsistent view of some data, that inconsistency happening because while it was running another thread was in the middle of changing data.

in your example, one thread is reading a structure and at the same time another is writing. suppose that there are two related fields:

  { foreground: red; background: black }

and the writer is in the process of changing those

   foreground = black;
            <=== window of opportunity
   background = red;

if the reader reads the values at just that window of opportunity then it sees a "nonsense" combination

  { foreground: black; background: black }

this essence of this pattern is that for a brief time, while we are making a change, the system becomes inconsistent and readers should not use the values. as soon as we finish our changes it becomes safe to read again.

hence we use the criticalsection apis mentioned by stefan to prevent a thread seeing an inconsistent state.

By Ransaka Ravihara on September 3 2022

Answers related to “thread safe programming”

Only authorized users can answer the Search term. Please sign in first, or register a free account.