c++ - 为什么实例member-fcn的cpp线程重置成员变量?

标签 c++ multithreading

我的简单测试代码如下:

// 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 不由 fcn1fcn2 共享?

演示代码是我实际使用的简化,但面临同样的问题,

我的代码有什么问题吗?非常感谢。

最佳答案

来自 std::thread :

args_copy... are objects of types std::decay<Args>::type... and constructed from std::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 or std::cref).

因此默认情况下会复制参数,包括 this指向成员函数的指针的参数。您可以将其包裹在 std::ref 中明确获取引用。

std::thread tt(&test::fcn1, std::ref(t));

关于c++ - 为什么实例member-fcn的cpp线程重置成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74793733/

相关文章:

java - Android Activity会关闭Looper&Handler吗?

multithreading - Kotlin中,一个线程一次只能运行一个协程?

c++ - 在标准下调用 std::function<void(Args...)> 是否非法?

c++ - 在这个简单的例子中安全地调用 new 的最佳方法是什么?

c++ - 使用列表向后打印字母表时缺少“a”

c++ - 在 C++ 中发送 HTML 格式电子邮件的简便方法

javascript - 如何使用 C++ 中的 V8 同时运行一堆 JS 代码?

python - 在 Python 中发出大量 HTTP 请求

java - 一个单例类来设计一副通用的牌?

c++ - C++是否保证从两个线程访问数组的相邻元素是安全的