0

Say I have a class:

class This
{ 
    void that(int a, int b);
};

and in my main function I need to start 'that' in a thread, and pass it 2 arguments. This is what I have:

void main()
{
   This t;
   t.that(1,2);  //works unthreaded.

   std::thread test(t.that(1,2)); // Does not compile. 'evaluates to a function taking 0 arguments'

   std::thread test2(&This::that, std::ref(t), 1, 2); //runs, but crashes with a Debug error.
}

I have searched, but have only found how to pass arguments to a thread, and to run a function from another class in a thread, but not both!

What is the correct way to do this?

2
  • What error does it crash with? thread terminated with a join? Commented Jun 17, 2015 at 14:26
  • stackoverflow.com/questions/10673585/… Commented Jun 17, 2015 at 15:07

3 Answers 3

3

In order to run This in another thread you either have to make a copy or ensure that it is still valid as long as the other thread is running. Try one of these:

Reference

This t;

std::thread test([&]() {
    t.that(1,2); // this is the t from the calling function
});

// this is important as t will be destroyed soon
test.join();

Copy

This t;

std::thread test([=]() {
    t.that(1,2); // t is a copy of the calling function's t
});

// still important, but does not have to be in this function any more
test.join();

Dynamic allocation

auto t = std::make_shared<This>();

std::thread(test[=]() {
    t->that(1,2); // t is shared with the calling function
});

// You still have to join eventually, but does not have to be in this function
test.join();
Sign up to request clarification or add additional context in comments.

Comments

2

The object t is destroyed at the end of the main() function, but the thread runs for some time after that. It results in an undefined behavior. It is also generally a good idea to join to all threads before quitting the program. Just put this at the end:

test2.join();

Comments

0

This::that does not take a reference to a This as its first argument.

I think what you want to do is more like

auto t = std::make_shared<This>();
std::thread test2{ [t](int a, int b) { t->that(a, b); }, 1, 2 };

Comments

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.