If there are n threads doing a read(uniqe_file[k], buffer, sizeof(buffer)) (k=1..n) (read from unistd.h) is there a chance that the content of buffer, after the threads are done, is messed up by having a combination of values from various files?
For example:
n = 2
buffer is a char array
unique_file[1] contains "abc"
unique_file[2] contains "123"
Then, can buffer contain, at the end, something like "a2c", or "12c" or even worse cases like "1a2"?
And, can you provide an explanation for the possible scenarios?
CodePudding user response:
Is there any race condition for 2 or more threads doing read from different files into the same buffer?
Yes: two threads attempting to write the same bytes is a race condition by definition. The resulting program exercises undefined behavior.
can buffer contain, at the end, something like "a2c", or "12c" or even worse cases like "1a2"
Undefined behavior means: anything can happen.
It's unlikely that you'll observe anything other than abc
or 123
, but it's possible for all of the above to happen. The conditions for 1a2
in particular are exceedingly unlikely, but it can happen.
Other unlikely possibilities: 111
, 231
, aca
, etc. To see why these are possible, read this article.