如何在类C++中制作四个线程

How to make four threads in a class C++

本文关键字:线程 四个 C++      更新时间:2023-10-16

我在一个类中创建四个线程时遇到问题,每个线程使用另一个成员函数打印出每个向量的内容。但是,当我制作线程时,我在这 4 行上收到错误no instance of constructor "std::thread::thread" matches the argument list。我不知道如果我尝试为线程使用另一个成员函数,为什么它不起作用。会不会是因为他们在课堂上?我将如何解决这 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