Creating a global thread

Started by
13 comments, last by Bregma 5 years, 1 month ago

Hi Guys,

How would I go about creating a global thread so I can fire it off in another function?

I have tried this but it won't compile.

call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type


std::thread t1;

int main()
{
	t1(functionToThread());
	t1.join();

	return 0;
}

Any advice on how to do this would be awesome.

Thanks in advance.

Advertisement

Assuming I interpreted the question correctly, i.e. call the function in the new thread.  Basically std::thread only supports construction time initialization and move semantics, no command operator (as you are attempting) nor copy semantics are allowed.  So, in order to do what I believe you want, something along the following lines should work:


std::thread t1;

int main()
{
	t1 = std::move(std::thread([](){ functionToThread(); }));
	t1.join();

	return 0;
}

Basically this means make a new thread instance with valid initialization data and move the result into the global t1.  Also, std::thread expects a std::function, so I threw a lambda around the call just to guarantee it will be in the correct form.

Hope this helps.

Hi @All8Up, thanks for the reply.

Visual studio isn't liking that much unfortunately.

binary '=': no operator found which takes a right-hand operand of type 'main::<lambda_d966b7089c91dae04de6f0bb66035a45>'

You can't do what you're trying to do: create an uninitialized thread object and initialize it later.

You might be able to create a thread at namespace scope.  You still have to initialize it.

Stephen M. Webb
Professional Free Software Developer

This should do it:


std::thread t1;
int main()
{
    t1 = std::thread(functionToThread);
    t1.join();
    return 0;
}
	
3 hours ago, DividedByZero said:

Hi @All8Up, thanks for the reply.

Visual studio isn't liking that much unfortunately.

Yup, late night goof.  I didn't actually make the thread..  Edited the post with corrected code.

5 hours ago, Eternal said:

This should do it:



std::thread t1;
int main()
{
    t1 = std::thread(functionToThread);
    t1.join();
    return 0;
}
	

you're going to need a std::move in there like All8Up posted.

2 hours ago, h8CplusplusGuru said:

you're going to need a std::move in there like All8Up posted.

The temporary is already an rvalue, so what's the std::move for? (And the lambda also isn't useful, if you don't need the capture.)

Awesome @All8Up, that worked perfectly. Many thanks!

2 hours ago, Eternal said:

The temporary is already an rvalue, so what's the std::move for? (And the lambda also isn't useful, if you don't need the capture.)

Well std::thread has a deleted assignment and instead a move-assignment, so normally you do explicit std::move. However, with the temporary it is not necessary.

This topic is closed to new replies.

Advertisement