anti
anti

Reputation: 3125

passing multiple arguments to a threaded function from another class

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?

Upvotes: 0

Views: 334

Answers (3)

KABoissonneault
KABoissonneault

Reputation: 2369

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 };

Upvotes: 0

Fozi
Fozi

Reputation: 5135

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();

Upvotes: 3

petersohn
petersohn

Reputation: 11720

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();

Upvotes: 2

Related Questions