I have an issue where a function in main thread is blocked until a local variable is set in another thread. I use semaphore to block the main thread execution:
int sendRequest(Message request, void *data)
{
semaphore waitForReply;
volatile int result = 0;
volatile int retData[100];
client->sendRequest(request, [&result, &retData](const Message& reply){ // Callback is called from a different thread
result = reply.result;
memcpy(retData, reply.retData, sizeof(retData));
waitForReply.signal();
})
waitForReply.wait();
//At this line we want result var to be updated.
memcpy(data, retData, sizeof(retData));
return result;
}
Question is does using volatile int result guarantee that the returning result is the actual value received from the callback? and is this the best way to solve this issue or using normal variable and mutex lock is better?
How about the case with array retData? (please don't mind the size of the array)
volatilein is not sufficient.volatileisn't doing anything useful, you should remove it. Your callback signals the semaphore only after the data has been copied out, so you are guaranteed to have correct data afterwait()returns. Or, to put in another way, it's not thevolatilethat guarantees correct behavior here. The guarantee comes fromsignal()being called after the data has been copied, and thatwait()will block and wait for that signal.