![](/img/trans.png)
[英]How to delegate a task to main thread and wait for it's execution to complete?
[英]How to make destructor wait until other thread's job complete?
我有一個主線程會將異步作業發送到另一個線程上的任務隊列。 而這個主線程可以隨時觸發銷毀動作,這可能導致程序在異步任務中崩潰,一段非常簡化的代碼如下:
class Bomb {
public:
int trigger;
mutex my_mutex;
};
void f1(Bomb *b) {
lock_guard<std::mutex> lock(b->my_mutex); //won't work! Maybe b have been destructed!
sleep(1);
cout<<"wake up.."<<b->trigger<<"..."<<endl;
}
int main()
{
Bomb *b = new Bomb();
b->trigger = 1;
thread t1(f1, b);
sleep(1);
//lock here won't work
delete b;//in actual case it is triggered by outside users
t1.join();
return 0;
}
f1 中的鎖不起作用,因為可以先調用析構函數並且嘗試讀取互斥鎖會崩潰。 出於同樣的原因,在析構函數中或在刪除之前加鎖也不起作用。
那么在這種情況下有沒有更好的方法呢? 我是否必須將互斥鎖放入全局 scope 和析構函數中才能解決問題?
在代碼中,我的評論如下所示:
#include <future>
#include <mutex>
#include <iostream>
#include <chrono>
#include <thread>
// do not use : using namespace std;
class Bomb
{
public:
void f1()
{
m_future = std::async(std::launch::async,[this]
{
async_f1();
});
}
private:
void async_f1()
{
using namespace std::chrono_literals;
std::lock_guard<std::mutex> lock{ m_mtx };
std::cout << "wake up..\n";
std::this_thread::sleep_for(1s);
std::cout << "thread done.\n";
}
std::future<void> m_future;
std::mutex m_mtx;
};
int main()
{
{
std::cout << "Creating bomb\n";
Bomb b; // no need to use unecessary new
b.f1();
}
std::cout << "Bomb destructed\n";
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.