Brief: In the Following code, main function creates 8 threads , producer fills the payload array one at a time ,waits for that particular consumer to read it and then moves on to the next index. The waiting mechanism is , waiting for the global value to be cleared by consumer.
//Producer
volatile int Payload[8];//global
CreateThread(); // 8 threads.
while(1)
{
for(int i = 0; i < 8;i++)
{
Payload[i] = 10;
while(Payload[i]==10); //this is done to wait till thread reads and clears it.
}
}
//Consumer
while(1)
{
if(Payload[threadindex])
{
x = Payload[threadindex];
Payload[threadindex] = 0;
cout << "print" << endl;
}
}
This does not work. Somehow I get stuck at
while(Payload[i]==0);
I think the issue is the following.
Even if I have kept Payload as volatile, program is still reading it from the cache and hence getting the stale value.
How can I force the threads to uncache the values?
How do I in general solve this problem? I am relatively new to Multi-threading.
Update: I see stackoverflow suggesting the following link.
Does guarding a variable with a pthread mutex guarantee it's also not cached?
Which mentions pthread functions doing memory barriers to ensure cache effects are made visible to other threads.
Do we have anything on windows?