繁体   English   中英

如何在另一个线程中创建互斥锁?

[英]How to make a mutex in another thread?

我想在一个循环中创建一个线程,当线程创建时,在线程完成之前不要再次创建它。 我使用下面的代码,但它不起作用,因为互斥锁会在它已经解锁时解锁。 谁能告诉我怎么办?

#include <iostream>
#include <thread>
#include <mutex>

int counter = 0;
std::mutex mtx;
std::thread t;

void test_mutex_t2()
{
 std::lock_guard<std::mutex> lock(mtx);
 counter++;
}

void test_mutex_t1()
{
 while (1) {
   if (mtx.try_lock())
   {
     t = std::thread(test_mutex_t2);    
     mtx.unlock();
   }
 }
}

int main()
{
  test_mutex_t1();
  return 0;
}

std::thread必须detachjoin

std::mutex mtx;
std::thread t;

void test_mutex_t2()
{
    std::lock_guard<std::mutex> lock(mtx);
    counter++;
}

void test_mutex_t1()
{
    while (1) {
        if (mtx.try_lock())
        {
            t = std::thread(test_mutex_t2);
            t.detach();
            mtx.unlock();
        }
    }
}

听起来您真正想要的是随时运行一个后台线程。 如果这是真的,我建议完全摆脱锁,在退出循环之前选择join()线程。 像这样的东西:

while (true) {
    auto thr = std::thread(test_mutex_t2);
    thr.join(); // Will block until thread exits
}

不过,我也想指出,这意味着你将有一个确切的线程中运行。 这就提出了一个问题,你为什么要使用线程? 您生成额外的线程只是为了进行同步工作。

如果您确实需要多个线程,则需要不同的同步原语。 从根本上说,互斥锁旨在保护对单个资源的访问。 你要做的是从后台线程传递给主线程,通知在后台线程所做的事(成品,在这种情况下)主线程什么。 这通常通过条件变量或信号量来完成。 std::condition_variable类实现了第一个。

我建议向线程函数传递一个条件变量,它用于在完成时提醒主线程。 像这样的东西:

void thread_func(std::condition_variable* cv) {
     // do work
     cv->notify_one();
}

int main(void) {
     std::condition_variable cv;
     std::mutex lock;
     while (true) {
         std::unique_lock<std::mutex> lock(mut);
         auto thr = std::thread(thread_func, &cv);
         cv.wait(lock); // Wait for background thread to notify us
         thr.join();
     }
}

同样,这对于这个简单的例子来说太过分了; 我会使用上面的join()方法。 但是如果你想要一个更复杂的通信模式,主线程需要在多个地方等待后台线程,条件变量更合适。

暂无
暂无

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

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