在另一个线程中执行一个方法

时间:2018-01-16 13:34:21

标签: c++

我想在另一个线程中执行DisplayWriters。不幸的是我得到了更多的信息:Invalid use of non static member function这是代码:

 void Chat::Init() {
    //some code

    thread writersThread(Chat::DisplayWriters);
}

void Chat::DisplayWriters() {
    for (auto &v : writers) {
        // do stuff
    }
}

我真的不能DisplayWriters静态,因为它使用writers类中的Chat列表。那我该怎么办呢?

1 个答案:

答案 0 :(得分:-1)

如果你真的要运行DisplayFunction异步,你应该做这样的事情。

class Chat {
    thread* writersThread = nullptr;
void Init() {
    //some code
    writersThread = new thread(&Chat::DisplayWriters, *this);
}

void DisplayWriters() {
    for (auto &v : writers) {
        // do stuff
    }
}
~Chat() {
    if(writersThread) {
        writersThread->join();
        delete writersThread;
    }
}
};