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

标签 c++ multithreading opencv camera

我对线程的概念完全陌生。

我必须使用一个线程从我的主程序更新来自相机的一些 cv::mat 变量。

我只知道线程意味着共享变量的问题:/

所以我认为我不能在主线程和线程中都使用通用变量

我在用

    #include <thread> 

这是我的线程fct:

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

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

    }

我在进入主循环(用于渲染)之前调用它。所以我的目标是在我的主要功能中访问 a 和 b。我该怎么做?

最佳答案

确实,如果你从多个线程访问你的ab变量,就会出现互斥的问题。这可以通过使用 mutex 来解决。您需要在读取和/或写入变量之前锁定互斥锁,然后解锁它。这可以通过 lock_guard 来完成。

你可以这样做:

#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;
}

关于c++ - 从主循环访问线程变量 - C++ - Windows,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23196460/

相关文章:

c++ - 什么时候可以在没有谓词的情况下使用 std::condition_variable?

c - 为什么 pthread_cond_signal() 没有被调用?

java - 如何进行延迟的非阻塞函数调用

visual-studio-2010 - 调试 CUDA 内核

c++ - 在openCV中设置某个图像中像素的RGB值

c++ - OpenCV inRange() 函数

c++ - OpenGL 着色器存储缓冲区/memoryBarrierBuffer

C++ - _beginthreadex() 不启动线程

java - 信号量 : Permit acquired in one thread can be released from another thread - Example

C++ Shell 多管道不工作?