为什么 std::thread 阻止执行?
Why is std::thread blocking execution?
我想在单独的线程中使用 class 方法 运行 :
std::thread myThread(&Class::method, this);
myThread.join();
//Other events
在执行此操作时,其他事件仅在 Class:method 结束时发生,而不是同时发生。
我忘记了什么?
您正在线程上调用 .join
(),该线程会阻塞直到该线程完成,以便与该线程同时进行 运行 事情或者在您完成的所有其他事情之后调用 join()
想要 运行 并发完成,或者在线程对象上调用 detach()
而不是
例如
auto th = std::thread{[]() { ... }};
do_something();
th.join();
在此示例中 do_something()
将 运行 与线程 th
并发,或者您可以调用 detach()
std::thread{[]() { ... }}.detach();
do_something();
事情是这样的:
启动线程并拥有它 运行 &Class::method
std::thread myThread(&Class::method, this);
等待线程结束。
myThread.join();
在当前线程中做其他事情
//Other events
如您所见,您的 myThread.join()
暂停了当前线程。
改为这样做:
std::thread myThread(&Class::method, this);
//Other events
myThread.join();
或者;不要执行该连接并改为调用 myThread.detach();。
我想在单独的线程中使用 class 方法 运行 :
std::thread myThread(&Class::method, this);
myThread.join();
//Other events
在执行此操作时,其他事件仅在 Class:method 结束时发生,而不是同时发生。
我忘记了什么?
您正在线程上调用 .join
(),该线程会阻塞直到该线程完成,以便与该线程同时进行 运行 事情或者在您完成的所有其他事情之后调用 join()
想要 运行 并发完成,或者在线程对象上调用 detach()
而不是
例如
auto th = std::thread{[]() { ... }};
do_something();
th.join();
在此示例中 do_something()
将 运行 与线程 th
并发,或者您可以调用 detach()
std::thread{[]() { ... }}.detach();
do_something();
事情是这样的:
启动线程并拥有它 运行 &Class::method
std::thread myThread(&Class::method, this);
等待线程结束。
myThread.join();
在当前线程中做其他事情
//Other events
如您所见,您的 myThread.join()
暂停了当前线程。
改为这样做:
std::thread myThread(&Class::method, this);
//Other events
myThread.join();
或者;不要执行该连接并改为调用 myThread.detach();。