1

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)
4
  • Visual Studio what? There have been many versions. Commented Jun 11, 2015 at 21:20
  • 1
    t1.join won't compile, you should always try to post your real code instead of typing it in on the spot. Commented Jun 11, 2015 at 21:39
  • i am using visual studio professional 2015 Commented Jun 11, 2015 at 21:53
  • I've edited to fix your other problem. You need to call join or else the tread will call std::terminate when it's destructor executes. Commented Jun 11, 2015 at 22:17

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

i did that, but now i have a new error. look at it on the update of my question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.