Reputation: 99
I've been trying to learn how to multi thread, but I could not the thread object to create properly. I have an object with a function called task, but when I add the function and the argument, it says the constructor doesn't take it. Btw im using visual studio as my IDE.
Here is my main file:
#include <iostream>
#include <thread>
#include "Task.h"
using namespace std;
int main(int argc, char** argv)
{
Task t;
thread t1(t.task, 1);
t1.join;
return 0;
}
the class of the Task Object:
#include "Task.h"
#include <iostream>
using namespace std;
Task::Task()
{
}
Task::~Task()
{
}
void Task::task(int x) {
cout << "In Thread " << x << '\n';
}
The error:Error: no instance of constructor"std::thread::thread" matches the argument list
argument types are: (<error-type>, int)
Update:
So i put in thread t1(&Task::task, &t, 1);
and got rid of t1.join
, but now i have a new problem. The program compilers and runs, but right when it runs, it displays "In Thread 1" in console, and another window comes up that says:
Debug Error!
abort() has been called
(Press retry to debug the application)
Upvotes: 1
Views: 1909
Reputation: 3342
The problem you have is that Task::task
is a member function. Member functions have a hidden parameter that is used as the this
pointer. To make that work you should pass an instance of the class to be used as the this
pointer. So initialize your thread like this
thread t1(&Task::task, &t, 1)
The other problem you have in your example is that join
isn't being called. t.join
doesn't actually call join
, you have to call it like this: t.join()
. If the destructor of a std::thread
executes and join
hasn't been called the destructor will call std::terminate
.
See here for more information on std::thread
's constructor and here for its destructor.
Upvotes: 5