Question

I'm completely new to the concept of thread.

I have to use a thread to update some cv::mat variable from camera from my main program.

I only know that thread mean problem to share variable :/

So I think that I can't use a general variable in both my main and in the thread

I'm using

    #include <thread> 

Here is my thread fct:

    void MyThreadFunction()
    {
        cv::Mat a;
        cv::Mat b;

        while (1)
        {
            capture_L.read(a);
            capture_R.read(b);
        }

    }

I'm calling it before entering in my main loop(for rendering). So my goal is to access a and b in my main function. How can I do that?

Was it helpful?

Solution

Indeed, if you access your a and b variables from several threads, there will be a problem of mutual exclusion. This can be solved by using a mutex. You need to lock the mutex before read and/or write the variables, and unlock it after. This can be done by lock_guard.

You can do something like that :

#include <mutex>
#include <thread>

void MyThreadFunction(mutex& m, cv::Mat& a, cv::Mat& b)
{
    while (1)
    {
        [ ... ]

        {
          lock_gard<mutex> l(m);
          capture_L.read(a);
          capture_R.read(b);
        }
    }

}

int main()
{
  mutex m;
  cv::Mat a, b;

  thread t(MyTjreadFunction, ref(m), ref(a), ref(b));

  {
     lock_gard<mutex> l(m);
     [ ... access a & b ... ]
  }

  t.join();

  return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top