别detach()了。
人们使用detach()的频率太高了。
它应该只在相对较少的情况下使用。在main结束后运行线程不是一个好主意,如果没有与线程结束的正式同步,防止这种情况基本上是不可能的。
使用detach()ed线程有两种方法可以做到这一点-- std::promise的_at_thread_exit方法,或者使用特定于操作系统的API。
线程池可能就是您想要的。
代码语言:javascript复制template
struct threadsafe_queue {
std::optional
T wait_and_pop();
void push(T);
std::deque
private:
mutable std::mutex m;
std::condition_variable cv;
std::deque
};
struct thread_pool {
explicit thread_pool( std::size_t number_of_threads );
std::size_t thread_count() const;
void add_thread(std::size_t n=1);
void abort_all_tasks_and_threads();
void wait_for_empty_queue();
~thread_pool();
template
std::future
private:
using task=std::future
std::vector
threadsafe_queue< task > tasks;
};大概是这样的东西。
然后创建一个单线程线程池,并将任务推入其中。

