c++ - 如何在C++类中创建四个线程

标签 c++ multithreading class vector

我在类中创建四个线程时遇到问题,每个线程都使用另一个成员函数来打印每个 vector 的内容。但是,当我创建线程时,我在这 4 行上收到错误 no instance of constructor "std::thread::thread"matches the argument list 。我不知道为什么如果我尝试为线程使用另一个成员函数它不起作用。难道是因为他们在一个类(class)里?我该如何修复这 4 个错误?

class PrintfourVectors
{
private:
    vector<string> one;
    vector<string> two;
    vector<string> three;
    vector<string> four;
public:
    void printOne()
    {
        // do stuff
    }

    void printTwo()
    {
        // do stuff
    }


    void printThree()
    {
        // do stuff
    }

    void printFour()
    {
        // do stuff
    }

    void makeFourThreads()
    {
        thread threadone(printOne);   // error here
        thread threadtwo(printTwo);   // error here
        thread threadthree(printThree); // error here
        thread threadfour(printFour); // error here

        threadone.join();
        threadtwo.join();
        threadthree.join();
        threadfour.join();

    }

};

最佳答案

一个问题是您正在调用非静态成员函数,并且这些函数有一个“隐藏”的第一个参数,该参数成为函数中的 this 指针。因此,当使用非静态成员函数创建线程时,您需要将对象实例作为参数传递给线程函数。

喜欢

thread threadone(&PrintfourVectors::printOne, this);
//                                            ^^^^
// Pass pointer to object instance as argument to the thread function

关于c++ - 如何在C++类中创建四个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37371150/

相关文章:

带有列表初始化的 C++11 嵌套映射

c# - Autofac - 解决多线程环境中的依赖关系

c++ - 如何将文本文件读入类的 vector

c++ - pcap_lookupdev 未定义

c++ - 可变参数模板 : One method per template argument

c++ - 使用stringstream 将string 转换为int 的效率如何?

multithreading - App Engine Channel API 的线程安全/原子性

c++ - 为什么这段代码会产生竞争条件?

python - 在python程序中定义类外的一些函数有什么好处

c++ - 如何使用一个类使一个变量可用于多个 .cpp 文件?