How to Notify Tail updates to threads in c++ windows? [Read uncached value for globals]

by Anup Buchke   Last Updated August 14, 2019 05:26 AM - source

//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.



Related Questions