Reputation: 3346
According to WaitOnAddress doc, WaitOnAddress
should block until the value at the given address changes.
#include <synchapi.h>
#include <thread>
#include <chrono>
using namespace std::chrono_literals;
#pragma comment(lib,"Synchronization.lib")
namespace __monitorVaribleChangeTest
{
void startAThreadToWaitAVaribleChange(int& a)
{
std::thread th([&a]() {
auto b = a;
cout << "WaitOnAddress start\n";
WaitOnAddress(&a, &b, sizeof(a), INFINITE);
cout << "WaitOnAddress passed\n";
});
th.detach();
}
void main()
{
int a = 100;
startAThreadToWaitAVaribleChange(a);
std::this_thread::sleep_for(3000ms);
a = 99;
std::this_thread::sleep_for(3000ms);
}
}
So, WaitOnAddress passed
is supposed to be shown after a = 99;
– but it never showed.
Upvotes: 1
Views: 1185
Reputation: 51835
According to the documentation that you linked, you will need to signal that the value at the given address has changed, by calling either WakeByAddressSingle
or WakeByAddressAll
:
The address on which to wait. If the value at Address differs from the value at CompareAddress, the function returns immediately. If the values are the same, the function does not return until another thread in the same process signals that the value at Address has changed by calling WakeByAddressSingle or WakeByAddressAll or the timeout elapses, whichever comes first.
The following version of your main
does what (I think) you expect:
void main()
{
int a = 100;
startAThreadToWaitAVaribleChange(a);
std::this_thread::sleep_for(3000ms);
a = 99;
WakeByAddressSingle(&a);
std::this_thread::sleep_for(3000ms);
}
Upvotes: 2