我有一个偶尔从GigE相机获取帧,并希望它快速返回的功能。标准程序是这样的:GetNextFrame()
后std ::互斥与RAII但在后台线程完成和释放
// ...
camera.StartCapture();
Image img=camera.GetNextFrame();
camera.StopCapture(); // <-- takes a few secs
return img;
返回数据已准备就绪,StopCapture()
是相当缓慢;因此,我想尽快返回img
,并产生一个后台线程来执行StopCapture()
。但是,在收购再次开始的情况下(不太可能),我希望通过互斥体保护访问。有些地方可能会抛出异常,所以我决定使用RAII风格的锁,它将在范围退出时释放。同时,我需要将锁转移到后台线程。像这样的东西(伪码):
class CamIface{
std::mutex mutex;
CameraHw camera;
public:
Image acquire(){
std::unique_lock<std::mutex> lock(mutex); // waits for cleanup after the previous call to finish
camera.StartCapture();
Image img=camera.GetNextFrame();
std::thread bg([&]{
camera.StopCapture(); // takes a long time
lock.release(); // release the lock here, somehow
});
bg.detach();
return img;
// do not destroy&release lock here, do it in the bg thread
};
};
我怎样才能将锁从调用者转移到后台线程产生?或者有更好的方法来处理这个问题吗?
编辑:CamIface
的实例有足够的使用寿命,请假设它永远存在。
我会将该线程附加到'CamIface'而不是分离它。 – Jarod42
http://stackoverflow.com/a/20669290/104774应该回答你的问题,虽然我更喜欢@PeterT的回答 – stefaanv
我不认为它像移动捕捉一样简单。 std :: mutex :: unlock必须在该互斥锁被锁定的同一线程上调用:http://en.cppreference.com/w/cpp/thread/mutex/unlock –