如何使用不同的线程访问Singleton类成员函数?

Ank*_*itG 3 c++ oop design-patterns c++11

我试图在使用单例实例的不同线程上运行print()和print(char ch)方法.

任何人都可以帮我解决为什么我会收到错误: -

错误C3867:'Singleton :: print':函数调用缺少参数列表; 使用'&Singleton :: print'创建指向成员的指针

错误C3867:'Singleton :: print':函数调用缺少参数列表; 使用'&Singleton :: print'创建指向成员的指针

错误C2661:'std :: thread :: thread':没有重载函数需要2个参数

还帮我纠正下面的代码给我.


class Singleton
{
private:
    Singleton()
    {}
    static Singleton* singletonInstance;
public:
    static Singleton* getSingletonInstance();
    void print()
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
        for (int i = 0; i < 100000; i++)
        {
            cout<<i<<endl;
        }
    }
    void print(char ch)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
        for (int i = 0; i < 100000; i++)
        {
            cout<<ch<<" "<<i<<endl;
        }
    }
};
Singleton* Singleton::singletonInstance = nullptr;
Singleton* Singleton::getSingletonInstance()
{
    if(!singletonInstance)
        singletonInstance=new Singleton();

    return singletonInstance;
}

int main()
{
    std::thread t1(Singleton::getSingletonInstance()->print);
    std::thread t2(Singleton::getSingletonInstance()->print,'T');
    t1.join();
    t2.join();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Moh*_* El 6

发布的代码有两个问题:

1-您将函数指针传递给线程的方式是错误的:

std::thread t1(Singleton::getSingletonInstance()->print);
Run Code Online (Sandbox Code Playgroud)

并且编译器正在抱怨并给你一个提示你如何将函数指针传递给线程.它说: 使用'&Singleton :: print'创建一个指向成员的指针

另外step1你必须以下列方式传递你的函数指针:

std::thread t1(&Singleton::print);
Run Code Online (Sandbox Code Playgroud)

Step2:设置Sigleton类的对象,属于该函数指针.

std::thread t1(&Singleton::print, Singleton::getSingletonInstance());
Run Code Online (Sandbox Code Playgroud)

但是只有当你没有重载函数print时才会起作用,因为编译器无法找到,你愿意调用哪个print.

另外现在我们来到第二个问题:如何解决重载函数的问题?

你有两个可能性:

1-你告诉编译器有关你想要调用哪个函数的帮助:

int main()
{
    using print1 = void (Singleton::*)();
    using print2 = void (Singleton::*)(char);
    std::thread t1(print1(&Singleton::print), Singleton::getSingletonInstance());
    std::thread t2(print2(&Singleton::print), Singleton::getSingletonInstance(), 'T');
    t1.join();
    t2.join();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

2-你使用lambda函数并直接调用函数:

int main()
{
    auto *s = Singleton::getSingletonInstance();
    std::thread t1([&s](){s->print();});
    std::thread t2([&s]() {s->print('T');});
    t1.join();
    t2.join();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

第二个更聪明,更容易理解