[英]C++ detached thread bug
在花了一天的时间解决一个神秘的错误之后,我寻求您的帮助。
当我运行下面的代码时,您是否理解为什么复制带有“ Hello 3”的输出?
#include <iostream>
#include <future>
#include <string>
#include <functional>
#include <type_traits>
#include <unistd.h>
template <class Fn, class... Args>
inline decltype(auto) runTerminateOnException(Fn&& fn, Args&&... args) {
try {
return std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
} catch (...) {
std::terminate();
}
}
struct RunTerminateOnExceptionInvoker {
template <class Fn, class... Args>
decltype(auto) operator()(Fn&& fn, Args&&... args) const {
return runTerminateOnException(std::forward<Fn>(fn), std::forward<Args>(args)...);
}
};
template <class Fn, class... Args>
inline decltype(auto) runAsyncTerminateOnException(Fn&& fn, Args&&... args) {
usleep(1000);
return std::async(std::launch::async, RunTerminateOnExceptionInvoker(), std::forward<Fn>(fn), std::forward<Args>(args)...);
}
template <class Fn, class... Args>
inline void runOnDetachedThreadTerminateOnException(Fn&& fn, Args&&... args) {
usleep(1000000);
std::thread(RunTerminateOnExceptionInvoker(), std::forward<Fn>(fn), std::forward<Args>(args)...).detach();
}
struct A {
template <class T>
static void g(double x, const std::shared_ptr<std::string> &s) {
T t{};
std::cout << "g() : x = " << x << ", *s = " << *s << ", t = " << t << std::endl;
}
static void f(double x, std::shared_ptr<std::string> &s1, std::shared_ptr<std::string> &s2, std::shared_ptr<std::string> &s3) {
printf("Coucou 1\n");
runAsyncTerminateOnException(g<double>, x, s1); // Working
printf("Coucou 2\n");
auto future1 = runAsyncTerminateOnException(g<double>, x, s2); // Working
printf("Coucou 3\n");
runOnDetachedThreadTerminateOnException(g<double>, x, s3); // Working
}
};
int main() {
auto s1 = std::make_shared<std::string>("Hello 1");
auto s2 = std::make_shared<std::string>("Hello 2");
auto s3 = std::make_shared<std::string>("Hello 3");
A::f(10., s1, s2, s3);
printf("Coucou 4\n");
return 0;
}
输出:
Coucou 1
g() : x = 10, *s = Hello 1, t = 0
Coucou 2
Coucou 3
g() : x = 10, *s = Hello 2, t = 0
Coucou 4
g() : x = 10, *s = Hello 3, t = 0
g() : x = 10, *s = Hello 3, t = 0
谢谢
您在这里有未定义的行为。 由于线程是分离的,因此您不能保证*s3
寿命与分离的线程一样长。 main
在您的分离工作线程完成执行之前结束,所有这些字符串都超出范围。
您必须按值传递共享指针,才能真正获得它们的引用计数能力。 目前,对于每个测试,您只是通过引用传递了一个shared_ptr
实例,这并不是特别有用。
如果将它们按值传递给A::f
,则事情将按预期进行 。
我无法完全弄清编译器在您的情况下正在做什么,并且对此特定结果感到有些惊讶,但是幸运的是,我只能说“这是UB”,然后将其保留在此;)
坦白说,我什至不确定让一个分离的线程通过main
的末尾是否有效,但是我会让其他人解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.