...

/

Solution: Try Different Synchronization Techniques

Solution: Try Different Synchronization Techniques

The solution to the challenge, "Exercise: Try Different Synchronization Techniques".

We'll cover the following...

Solution

std::atomic_flag

Press + to interact
#include <iostream>
#include <atomic>
#include <thread>
#include <vector>
std::vector<int> mySharedWork;
std::atomic_flag atomicFlag;
void waitingForWork(){
std::cout << "Waiting " << std::endl;
atomicFlag.wait(false);
mySharedWork[1] = 2;
std::cout << "Work done " << std::endl;
}
void setDataReady(){
mySharedWork = {1, 0, 3};
std::cout << "Data prepared" << std::endl;
atomicFlag.test_and_set();
atomicFlag.notify_one();
}
int main(){
std::cout << std::endl;
std::thread t1(waitingForWork);
std::thread t2(setDataReady);
t1.join();
t2.join();
for (auto v: mySharedWork){
std::cout << v << " ";
}
std::cout << "\n\n";
}

The thread preparing the work sets the ...