我的简单测试代码如下:
// t.cpp
#include <iostream>
#include <thread>
#include <chrono>
class test
{
private:
public:
void fcn1();
void fcn2();
uint8_t i = 0;
};
void test::fcn1()
{
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(999));
std::cout << "hihi " << (float)i++ << std::endl;
}
}
void test::fcn2()
{
std::cout << "yoyo " << (float)i++ << std::endl;
}
test t;
std::thread tt(&test::fcn1, t);
int main()
{
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
t.fcn2();
}
return 0;
}
通过g++ ./t.cpp -o t -lpthread编译运行; ./t
,结果就像
hihi 0
yoyo 0
hihi 1
yoyo 1
hihi 2
yoyo 2
hihi 3
...
我预计结果应该是:
hihi 0
yoyo 1
hihi 2
yoyo 3
hihi 4
yoyo 5
...
看起来实例member-fcn的cpp线程重置了成员变量?
为什么 i
不由 fcn1
和 fcn2
共享?
演示代码是我实际使用的简化,但面临同样的问题,
我的代码有什么问题吗?非常感谢。
最佳答案
来自 std::thread
:
args_copy...
are objects of typesstd::decay<Args>::type...
and constructed fromstd::forward<Args>(args)....
...
The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g., with
std::ref
orstd::cref
).
因此默认情况下会复制参数,包括 this
指向成员函数的指针的参数。您可以将其包裹在 std::ref
中明确获取引用。
std::thread tt(&test::fcn1, std::ref(t));
关于c++ - 为什么实例member-fcn的cpp线程重置成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74793733/