我有以下代码在专用线程上运行函数。除了析构函数外,它工作得很好。调用thread_.join()
不返回。我正在使用 VS2013 Express。
我会改变什么以使线程正确连接?
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <vector>
namespace
{
class main_thread
{
public:
static auto instance() -> main_thread&
{
static main_thread instance_;
return instance_;
}
auto enque(std::function<void()> func) -> void
{
{
std::lock_guard<std::mutex> lock{ mutex_ };
queue_.push_back(func);
}
condition_.notify_one();
}
private:
main_thread()
{
continue_.test_and_set();
thread_ = std::thread{ std::bind(std::mem_fn(&main_thread::run), this) };
}
~main_thread()
{
continue_.clear();
condition_.notify_all();
if (thread_.joinable())
{
thread_.join();
}
}
main_thread(const main_thread &other) = delete;
main_thread(main_thread &&other) = delete;
main_thread& operator=(const main_thread &other) = delete;
main_thread& operator=(main_thread &&other) = delete;
auto run() -> void
{
while (continue_.test_and_set())
{
auto lock = std::unique_lock<std::mutex>{ mutex_ };
//condition_.wait_for(lock, std::chrono::milliseconds(1));
condition_.wait(lock);
for (auto &func : queue_)
{
func();
}
queue_.clear();
}
}
std::condition_variable condition_;
std::mutex mutex_;
std::vector<std::function<void()>> queue_;
std::thread thread_;
std::atomic_flag continue_;
};
}
auto on_main_thread(std::function<void()> func) -> void
{
main_thread::instance().enque(std::move(func));
}
auto on_main_thread_sync(std::function<void()> func) -> void
{
bool done{ false };
on_main_thread([&]{
func();
done = true;
});
while (!done);
}
执行此代码的唯一功能是
int main()
{
on_main_thread([]{});
}
这避免了比赛的问题,on_main_thread_sync
但仍然有锁定~main_thread
。Visual Studio 表示有 2 个线程,但都不是 in main_thread::run
,所以我不明白发生了什么。该函数正确退出,但由于某种原因线程没有结束。