[英]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
必須detach
或join
:
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.