简体   繁体   English

从主循环访问线程变量-C ++-Windows

[英]access to a thread variable from main loop - c++ - windows

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. 我必须使用线程从我的主程序中的相机更新一些cv :: mat变量。

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: 这是我的线程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. 因此,我的目标是访问主函数中的a和b。 How can I do that? 我怎样才能做到这一点?

Indeed, if you access your a and b variables from several threads, there will be a problem of mutual exclusion. 实际上,如果您从多个线程访问ab变量,将存在相互排斥的问题。 This can be solved by using a mutex . 这可以通过使用mutex来解决。 You need to lock the mutex before read and/or write the variables, and unlock it after. 您需要在读取和/或写入变量之前先lock互斥锁,然后再对其进行unlock This can be done by lock_guard . 这可以通过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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM