dimanche 24 avril 2016

Not able to call class member function in a separate thread using C++11 thread class

I am having a hard time to get the right syntax for calling a class member function in separate thread . Neither of the three options are working . Line 1 and 2 are throwing compile time error while the third one is showing run time error . Can anybody tell me please what is the correct way .

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
struct Complex 
{
    mutex mx;
    int i;
    Complex(int q) : i(q) {}
    void mul(int x) 
    {
        lock_guard<mutex> lock(mx);
        int z = i*x;
        cout<<z<<endl;
    }
    void div(int x)
    {
        lock_guard<mutex> lock(mx);
        int z = i/x;
        cout<<z<<endl;
    }
    void both(int x, int y) 
    {
         mul(x);
         div(y);
    }
};
int main()
{
    //Complex complex(9);
    //thread t(&Complex::both,&Complex(9),32, 23);     --1
    //thread t(&Complex::both,complex,32,23);          --2
    //thread t(&Complex::both,&complex,32,23);         --3
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire