Cpp:如何使用需要指针的方法创建线程?

时间:2018-04-23 17:45:28

标签: c++ multithreading

我想创建一个在工作完成后自动join的线程。所以,我写了以下代码:

#include <iostream>
#include <thread>
#include <chrono>
#include <future>

using namespace std;

class Foo
{
public:
    void work(atomic_bool & isWorking);

};

void Foo::work(atomic_bool & isWorking)
{
    //dosomestuff;
    int myVar = 0;
    while (myVar != 5)
    {
        myVar++;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    isWorking = true;
    return;
}

int main()
{
    std::atomic<bool> imdone;
    imdone = false;
    std::thread t1(&Foo::work, Foo(), imdone);

    while (true)
    {
        std::cout << "Is Joinable: " << t1.joinable() << "\n";
        if (imdone)
        {
            imdone = false;
            t1.join();
        }
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    cin.get();
}

我认为我可以传递这样的参数:std::thread t1(&Foo::work, Foo(), imdone);,但不是在参数是指针的情况下。在这种情况下,我如何使用指针传递指针?

1 个答案:

答案 0 :(得分:2)

您创建了一个您要调用其成员的类型的对象,并传递 地址,如下所示:

Foo foo; // create an object
std::thread t1(&Foo::work, &foo, ...); // pass its address

此外,您传递参考,因此您需要使用std::ref,如下所示:

Foo foo; // create an object
std::thread t1(&Foo::work, &foo, std::ref(imdone)); // use std::ref()