我想创建一个容器,可以将函数推入该容器,该容器将立即在线程中启动。功能完成后,应自动将其从容器中移除,以免容器无限期地增长。
到目前为止是我的尝试:
#include <thread>
#include <future>
#include <iostream>
#include <map>
class j_thread {
std::thread thread;
public:
j_thread() {}
template<typename F>
j_thread(const F& f) : thread(f) {}
j_thread& operator = (j_thread&& other) {
this->thread.swap(other.thread);
return *this;
}
virtual ~j_thread() {
thread.join();
}
};
class jobs {
std::map<size_t, j_thread> threads;
public:
template<typename F>
void add_job(const F &function) {
size_t job_id = threads.size();
auto wrapped_function = [&function, job_id, this]() {
function();
threads.erase(job_id);
};
threads[job_id] = j_thread(wrapped_function);
}
void wait_for_all() {
while(threads.size() != 0) {}
}
};
int main() {
jobs j;
j.add_job([](){std::cout << "hello" << std::endl;});
j.add_job([](){std::cout << "world" << std::endl;});
j.wait_for_all();
}
但是运行时出现错误:
terminate called after throwing an instance of 'std::system_error'
what(): Invalid argument
hello
terminate called recursively
12:15:44: The program has unexpectedly finished.
在线程体内调用join
是未定义的行为。
查看join的错误条件:
错误条件resource_deadlock_would_occur如果this-> get_id()==std :: this_thread :: get_id()(检测到死锁)
您的身体是:
auto wrapped_function = [&function, job_id, this]() {
function();
threads.erase(job_id);
};
在您调用erase
的地方,正在调用jthread
的dtor,它在可连接线程上调用了join
。
而不是join
,在您应该呼叫detach
。
为避免悬空参考,必须按值捕获function
。
[另外,调用size
和erase
时,您还必须添加一些互斥体以避免地图上的数据争用:
std::mutex m;
int size() {
std::lock_guard<std::mutex> lock{m};
return threads.size();
}
auto wrapped_function = [f = function, job_id, this]() {
f();
std::lock_guard<std::mutex> l(m);
threads.erase(job_id);
};
void wait_for_all() {
while(size() != 0) {}
}