Correct approach for non-blocking user input

Hi

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58


#include <iostream>
#include <thread>
#include <mutex>

using namespace 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.

Thanks
Last edited on
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 
Last edited on
Topic archived. No new replies allowed.