0

I am started writing my first thread tutorial, I am creating a single thread producer and consumer. It is not completed yet, synchronization is remaining. But it is not compiling, I am not understanding what that error means what argument is missing or wrong. Below is my code.

#include<iostream>
#include<thread>
#include<sstream>
#include<list>
#include<mutex>
#include<Windows.h>

using namespace std;

#define BUCKET_LEN 5

HANDLE gMutex = NULL;
HANDLE gSemFull = NULL;
HANDLE gSemEmpty = NULL;

class producerConsumer  {
    long i;
    list<wstring> que;
public:
    producerConsumer() {
        i = 0;
        que.clear();
    }
    void produce();
    void consumer();
    void startProducerConsumer();
};

void producerConsumer::produce() {
    std::wstringstream str;
    str << "Producer["  <<"]\n";
    que.push_back(str.str());
}

void producerConsumer::consumer() {
    wstring s = que.front();
    cout << "Consumer[" << "]";
    wcout << " " << s;
    que.pop_front();
}

void producerConsumer::startProducerConsumer() {
    std::thread t1(&producerConsumer::produce);
    std::thread t2(&producerConsumer::consumer);
    t1.joinable() ? t1.join() : 1;
    t2.joinable() ? t2.join() : 1; 
}

int main()
{
    gMutex = CreateMutex(NULL, FALSE, NULL);
    if (NULL == gMutex) {
        cout << "Failed to create mutex\n";
    }
    else {
        cout << "Created Mutex\n";
    }

    producerConsumer p;
    p.startProducerConsumer();

    if (ReleaseMutex(gMutex)) {
        cout << "Failed to release mutex\n";
    }
    else {
        cout << "Relested Mutex\n";
    }
    gMutex = NULL;
    system("pause");
    return 0;
}
Jonas
  • 6,915
  • 8
  • 35
  • 53
Dipak
  • 672
  • 3
  • 9
  • 26

1 Answers1

3

Non-static member functions needs an object to be called on. This object can be passed (as a pointer or reference) as a second argument to the std::thread constructor:

std::thread t1(&producerConsumer::produce, this);
std::thread t2(&producerConsumer::consumer, this);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • please give brief answer it will be more helpful, what mean by non static – Dipak May 29 '17 at 08:44
  • 1
    @Dipak A "static member function" is one declared using the `static` keyword, as in `struct Foo { static void static_member_function() { ... } };`. A non-static member function is a member function *without* the `static` keyword. Static member functions are also called *class functions* since they exists for the class/struct, not for specific objects. As such they have no `this` pointer. [Any good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) would have told you this. – Some programmer dude May 29 '17 at 08:46