使用成员函数启动线程应该传递对象,指针或参考?

发布于 2025-02-13 14:52:24 字数 597 浏览 1 评论 0原文

我对使用成员函数启动线程感到困惑。我知道我需要将类对象作为第二个参数传递。但是有人将对象传递给thread(),然后有人通过了一个地址,我试图通过参考。他们俩都在编译正常。因此,我对哪个是正确的困惑。

class X
{
    public:
        void do_lengthy_work(){
            std::cout << "1:1" << std::endl;
        }
};


int main(){
    X my_x;
    std::thread t(&X::do_lengthy_work, std::ref(my_x)); // pass reference
    std::thread t(&X::do_lengthy_work, &my_x);          // pass address
    std::thread t(&X::do_lengthy_work, my_x);           // pass object
    t.join();
    return 0;
}

I'm confused about starting a thread with a member function. I know I need to pass a class object as the second parameter. But someone passed the object to the thread(), and someone passed an address, and I had tried to pass a reference. Both of them are compiling OK. So I am confused about which one is correct.

class X
{
    public:
        void do_lengthy_work(){
            std::cout << "1:1" << std::endl;
        }
};


int main(){
    X my_x;
    std::thread t(&X::do_lengthy_work, std::ref(my_x)); // pass reference
    std::thread t(&X::do_lengthy_work, &my_x);          // pass address
    std::thread t(&X::do_lengthy_work, my_x);           // pass object
    t.join();
    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

腻橙味 2025-02-20 14:52:24

线程构造器开始根据 std ::::::::std ::::::::调用 。因此,您显示的所有代码行都将做点什么。

如果对象的寿命比线程的寿命更长,则前两行(参考和指针)很好。从上面的链接到std :: Invoke,它们是等效的。否则,第三行将对象复制到线程中。这意味着现在原始对象无关紧要,并且可以被销毁,但也意味着在原始对象(仅副本)中不会看到任何结果。

The thread constructor begins executing the thread according to the rules of std::invoke. So all 3 of the lines of code you show will do something.

The first two lines (ref and pointer) are fine if you expect the lifetime of the object to be longer than the lifetime of the thread. As you can see from the link to std::invoke above, they are equivalent. Otherwise, the third line copies the object into the thread. This means that the original object now doesn't matter and can be destroyed, but also means that any results will not be visible in the the original object, only the copy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文