I come from a C# background and I have a bit of a tough time with concurrency in C. I am not going to lie to you... This is part of a project I have to do for school. Although professionally I have worked with high level languages, my senior thesis professor threw us under the bus by forcing the entire class to code in C (which most of us have little to no experience with... :( ).
Either case, back to the problem. I have a global integer variable (starting from 0) which needs to be simultaneously incremented by 5 processes until it reaches 100 (100% rather).
Basically what's happening is that instead of individually modifying the completionCounter each child process is making a copy of it...
Is there a lock(object)
or something of the sort as it is available in C#? I tried using a binary semaphore but I couldn't get it to work, i haven't played with shared memory yet.
const int THREADCOUNT = 5;
int completionCounter = 0;
int main(int argc, char **argv)
{
int count = 0;
pid_t pid;
for(count = 0; count<THREADCOUNT; count++)
{
if( (pid = fork()) < 0 )
{
//error...
return -1;
}
else if( pid == 0 )
{
//child;
while(completionCounter != 100 )
{
printf("[%i] process downloading data chunk...", getpid());
//do stuff here
completionCounter += 5;
}
}
else
{
//parent.
}
}
}