I'm having trouble analyzing a problem on a past OS exam. It is as follows:
Describe the output of the following program. Does a race condition exist?
int count=0;
int main(void)
{
pid_t pid;
if( (pid = fork()) < 0)
{
perror("Fork error");
exit(1);
}
else if( pid == 0)
{
charatatime("Output 1\n");
}
else
{
charatatime("Output 2\n");
}
printf(“Count = %d”,count);
exit(0);
}
static void charatatime(char * str)
{
char * ptr;
int c;
for(ptr = str; c = *ptr++; )
{
count++;
putc(c, stdout);
}
}
I'm not that good yet with C and race conditions, so my answer is mostly a guess. But if I saw this on an exam, I would say "The program splits a process into a parent and child process; the child process prints 'Output1' and the parent prints 'Output2', one character at a time. Then the total number of letters is printed at the end of the program; however, this variable 'count' may be inaccurate, as a race condition exists between the child and parent. Either can access and update count at any time, which can lead to inaccuracies."
From my understanding, race conditions arise when two or more threads or processes try to access or set the same shared variable, and the only incident of that I can see in this program is 'count'. Am I anywhere near correct, and if not, what could be added to this program to create a race condition (hypothetically, of course; I know that's not what we would want to do)?
A simple example of a race condition is a light switch. In some homes, there are multiple light switches connected to a common ceiling light. When these types of circuits are used, the switch position becomes irrelevant. If the light is on, moving either switch from its current position turns the light off.
A race condition or race hazard is the condition of an electronics, software, or other system where the system's substantive behavior is dependent on the sequence or timing of other uncontrollable events. It becomes a bug when one or more of the possible behaviors is undesirable.
To avoid race conditions, any operation on a shared resource – that is, on a resource that can be shared between threads – must be executed atomically. One way to achieve atomicity is by using critical sections — mutually exclusive parts of the program.
A race condition occurs when two threads access a shared variable at the same time. The first thread reads the variable, and the second thread reads the same value from the variable.
As far as count
is concerned, there is no race: each of the two processes has its own separate count
.
As to the order in which the characters of "Output 1"
and "Output 2"
appear on stdout
, there is indeed a race: the two outputs can end up arbitrarily interleaved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With