I have an application where I need an object to be updated by user input without blocking another function which reads that object at any given time. I think this requires using two separate threads:
#include <iostream>
#include <thread>
#include <mutex>
usingnamespace std;
class MyObject
{
private:
int x;
public:
int getX() const
{
return x;
}
void setX(int num)
{
x = num;
}
};
mutex mtx;
void updateObjFromUserInput(MyObject &obj)// pass by reference as we want to update
{
while (true) // loop forever
{
std::lock_guard<std::mutex> lck (mtx); // prevent writing to obj whilst being read
int num;
cin >> num; // just an example (could be lots of write accesses to obj in function)
obj.setX(num);
}
}
void readObj(const MyObject &obj) // pass by const reference as only reading
{
while (true) // loop forever (there may be delays in this function)
{
std::lock_guard<std::mutex> lck (mtx); // prevent obj being read whilst written to
cout << obj.getX(); // just as an example
}
}
int main()
{
MyObject obj;
thread threadForUserUpdate(updateObjFromUserInput, ref(obj));
thread threadForRead(readObj, cref(obj));
threadForUserUpdate.join();
threadForRead.join();
}
Is the basic idea here correct? Appreciate that the above will need to be significantly refined but would be useful to know whether I am on the right lines re non-blocking user input.
when you reach cin >> num; line, the current thread execution will stop waiting for user input. the other threads will keep running.
but you went and put the mutex and block it ¿?
consider instead
1 2 3
cin >> num; // blocks this thread waiting for user input
std::lock_guard<std::mutex> lck (mtx); // we have input, now block the other threads
obj.setX(num); // modify the object