我有一個偶爾從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 –