I very recently started coding in C++11. Since I understood theoritical part, I thought of experimenting by writing code. This is my first program in C++, what it does is - I am creating a class which has a thread type member and 2 member functions, of which one is a thread function and the other is a function which starts this thread function. But I am facing the below error. I did a lot of Googling, but none of them helped. I want to spawn 2 threads of "runThread" and they will update the counter. I know the counter is not synchronised, but i will take care of that using std::atomic variable once this error gets resolved.Please advice.
#include <iostream>
#include <stdio.h>
#include <thread>
#include <vector>
class Application {
public:
Application(int val): counter(val) { printf("value is %d\n", counter); }
void start();
void print();
private:
void runThread();
int counter;
std::vector<std::thread> thr;
};
void Application::runThread() {
for(int i=0;1<50;i++)
counter++;
}
void Application::start() {
//std::thread t1(runThread);
//std::thread t2(runThread);
//this->thr.emplace_back(std::thread(&Application::runThread, this)); Tried this, but dint work
//this->thr.emplace_back(std::thread(&Application::runThread, this));Tried this, but dint work
thr.emplace_back(std::thread(runThread));
thr.emplace_back(std::thread(runThread));
}
void Application::print() {
printf("Counter = %d\n", counter);
}
int main(void)
{
int a;
Application app(300);
app.start();
std::cin >>a;
}
This is the error
../main.cpp: In member function ‘void Application::start()’:
../main.cpp:27:40: error: invalid use of non-static member function
thr.emplace_back(std::thread(runThread));
^
../main.cpp:28:40: error: invalid use of non-static member function
thr.emplace_back(std::thread(runThread));
^
subdir.mk:18: recipe for target 'main.o' failed
make: *** [main.o] Error 1
Aucun commentaire:
Enregistrer un commentaire