C++ - 当向量传递到方法时,怪异的线程行为
我编写了以下代码,并注意到了怪异的行为。
#include <iostream>
#include <vector>
#include <thread>
void withVectorArg(double waitTime, std::vector<int> q = {}) {
std::cout << "[withVectorArg] waitTime: " << waitTime << "s" << '\n';
std::thread thread([&waitTime]() {
std::cout << "[withVectorArg] waitTime: " << waitTime << "s" << '\n';
});
thread.detach();
}
void withoutVectorArg(double waitTime) {
std::cout << "[withoutVectorArg] waitTime: " << waitTime << "s" << '\n';
std::thread thread([&waitTime]() {
std::cout << "[withoutVectorArg] waitTime: " << waitTime << "s" << '\n';
});
thread.detach();
}
int main() {
withVectorArg(1);
std::this_thread::sleep_for(std::chrono::seconds(1));
withoutVectorArg(1);
while (true) {}
return 0;
}
该代码的输出是:
[withVectorArg] waitTime: 1s
[withVectorArg] waitTime: 3.38411e-312s
[withoutVectorArg] waitTime: 1s
[withoutVectorArg] waitTime: 1s
两种方法都完全相同,并且不使用Q
变量,但是第一个以某种方式更改了waittime
的值。
有人知道为什么会发生这种情况吗?
谢谢你!
I wrote the following code and noticed a weird behavior.
#include <iostream>
#include <vector>
#include <thread>
void withVectorArg(double waitTime, std::vector<int> q = {}) {
std::cout << "[withVectorArg] waitTime: " << waitTime << "s" << '\n';
std::thread thread([&waitTime]() {
std::cout << "[withVectorArg] waitTime: " << waitTime << "s" << '\n';
});
thread.detach();
}
void withoutVectorArg(double waitTime) {
std::cout << "[withoutVectorArg] waitTime: " << waitTime << "s" << '\n';
std::thread thread([&waitTime]() {
std::cout << "[withoutVectorArg] waitTime: " << waitTime << "s" << '\n';
});
thread.detach();
}
int main() {
withVectorArg(1);
std::this_thread::sleep_for(std::chrono::seconds(1));
withoutVectorArg(1);
while (true) {}
return 0;
}
The output of this code is:
[withVectorArg] waitTime: 1s
[withVectorArg] waitTime: 3.38411e-312s
[withoutVectorArg] waitTime: 1s
[withoutVectorArg] waitTime: 1s
Both methods do exactly the same and do not use the q
variable, yet the first one somehow changes the value of waitTime
.
Does someone know why this happens?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的两个功能都是不确定的行为。
原因是您正在启动线程,将其分离并立即退出功能。但是,该线程是通过参考捕获参数的,因此,当执行线程主体中的代码(可能是在您已经从函数返回之后发生的)局部变量,该局部变量限制为不再存在从功能返回时被破坏)。
当您进入UB领域时会发生什么是不确定的,试图解释确切的怪异行为是浪费时间。
Both your functions are undefined behavior.
The reason is that you're starting a thread, detaching it and exiting the function immediately. The thread however is capturing the parameter BY REFERENCE and thus when the code in the thread body is executed (that MAY happen AFTER you already returned from the function) the local variable that the reference is bound to does not exist any more (that local was destroyed when returning from the function).
What happens when you enter the UB realm is simply undefined, trying to explain the exact weird behavior is a waste of time.