Reputation: 2600
I'm having a problem with my C code where I declare a static int variable (as a flag), then initialize it to -1 in init() which is only called once, then when I try to update the value to 0 or 1 later on, it keeps reverting back to -1.
Does anyone know what the problem can be?
I don't have any local variables with the same identifier so I'm really lost.
Thanks!
static int previousState;
void init()
{
previousState = -1;
}
void moveForward(int currentState)
{
if (previousState == -1)
previousState = currentState;
if (previousState != currentState)
{
/* do stuff */
/* PROBLEM: it never goes into here, because previousState is always -1! */
}
/* other code */
}
void main()
{
init();
if (fork() == 0)
{
/* do stuff */
moveForward(1);
exit();
}
/* more forks */
moveForward(0);
exit();
}
Upvotes: 1
Views: 1421
Reputation: 62797
Each process calls moveForward just once. Processes do not share static data!
Use threads, or use shared memory. Also use mutex or semaphore for concurrent access of shared data . Preferably switch to a language better suited for parallel prosessing...
Upvotes: 3