[英]Conditionally acquire an std::mutex
I have a multi-threaded app that uses the GPU, which is inherently single-threaded, and the actual APIs I use, cv::gpu::FAST_GPU
, does crash when I try to use them multi-threaded, so basically I have: 我有一个使用GPU的多线程应用程序,它本质上是单线程的,而我尝试使用的实际API cv::gpu::FAST_GPU
确实在尝试使用多线程时崩溃了,所以基本上:
static std::mutex s_FAST_GPU_mutex;
{
std::lock_guard<std::mutex> guard(s_FAST_GPU_mutex);
cv::gpu::FAST_GPU(/*params*/)(/*parameters*/);
}
Now, benchmarking the code shows me FAST_GPU()
in isolation is faster than the CPU FAST()
, but in the actual application my other threads spend a lot of time waiting for the lock, so the overall throughput is worse. 现在,对代码进行基准测试后,我发现FAST_GPU()
的隔离度比CPU FAST()
要快,但在实际应用程序中,我的其他线程花费大量时间等待锁定,因此总体吞吐量更糟。
Looking through the documentation, and at this answer it seems that this might be possible: 查看文档,并在此答案看来,这可能是可能的:
static std::mutex s_FAST_GPU_mutex;
static std::unique_lock<std::mutex> s_FAST_GPU_lock(s_FAST_GPU_mutex, std::defer_lock);
{
// Create an unlocked guard
std::lock_guard<decltype(s_FAST_GPU_lock)> guard(s_FAST_GPU_lock, std::defer_lock);
if (s_FAST_GPU_lock.try_lock())
{
cv::gpu::FAST_GPU(/*params*/)(/*parameters*/);
}
else
{
cv::FAST(/*parameters*/);
}
}
However, this will not compile as std::lock_guard
only accepts a std::adopt_lock
. 但是,由于std::lock_guard
仅接受std::adopt_lock
,因此不会编译。 How can I implement this properly? 如何正确实施?
It is actually unsafe to have a unique_lock
accessible from multiple threads at the same time. 从多个线程同时访问unique_lock
实际上是不安全的。 I'm not familiar with the opencv portion of your question, so this answer is focused on the mutex/lock usage. 我对您问题的opencv部分不熟悉,因此该答案集中在互斥锁/锁用法上。
static std::mutex s_FAST_GPU_mutex;
{
// Create a unique lock, attempting to acquire
std::unique_lock<std::mutex> guard(s_FAST_GPU_mutex, std::try_to_lock);
if (guard.owns_lock())
{
cv::gpu::FAST_GPU(/*params*/)(/*parameters*/);
guard.unlock(); // Or just let it go out of scope later
}
else
{
cv::FAST(/*parameters*/);
}
}
This attempts to acquire the lock, if it succeeds, uses FAST_GPU
, and then releases the lock. 如果成功,它将尝试获取锁,使用FAST_GPU
,然后释放锁。 If the lock was already acquired, then goes down the second branch, invoking FAST
如果已经获取了锁,则转到第二个分支,调用FAST
You can use std::lock_guard
, if you adopt the mutex in the locked state, like this: 如果在锁定状态下采用互斥锁,则可以使用std::lock_guard
,如下所示:
{
if (s_FAST_GPU_mutex.try_lock())
{
std::lock_guard<decltype(s_FAST_GPU_lock)> guard(s_FAST_GPU_mutex, std::adopt_lock);
cv::gpu::FAST_GPU(/*params*/)(/*parameters*/);
}
else
{
cv::FAST(/*parameters*/);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.