Not able to declare a thread inside a for loop..

When I run this snippet, I get an abort from the program when it reaches the declaration of the thread inside the for-loop.

1
2
3
4
	for (;;) {
		std::thread on_finish_thread(do_nothing);
		break;
	}


do_nothing is defined as:

1
2
3
void do_nothing() {

}



Not having a for-loop, though, works fine
1
2
		std::thread on_finish_thread(do_nothing);
		break;


I'm so confused.
I don't know if it's worth mentioning..
but

1
2
3
4
for (;;) {
		std::thread on_finish_thread(do_nothing);
		on_finish_thread.join();
	}

works as well.

I have never used threads before by the way.

small example program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
#include<thread>

void do_nothing() {
}

int main()
{
	for (;;) {
		std::thread th(do_nothing);
		break;
	}

	std::cin.get();
	return 0;
}
Last edited on
http://www.cplusplus.com/reference/thread/thread/detach/
Well yes, it blows up because you have a joinable thread and your on_finish_thread variable goes out of scope before your thread exits and can be joined.

This also works
1
2
    std::thread on_finish_thread(do_nothing);
    on_finish_thread.detach();



> I have never used threads before by the way.
Expect a tough time then.
https://en.wikipedia.org/wiki/Race_condition#Software

Thanks for replying salem c.
using std::thread::detach() or simply declaring the thread before the loop fixed my problem.

Any suggested sources for learning threading with C++ (since I made a thread anyway)?
Last edited on
I would suggest you do a lot of background reading first, to make sure you're familiar with terminology, techniques etc.
https://en.wikipedia.org/wiki/Category:Concurrent_computing

Imagine, the hardest single threaded bug you've ever had to solve rates about a 10 on a scale of 1 to 10.

The hardest concurrency bug on the same scale will be about 1000.
https://en.wikipedia.org/wiki/Heisenbug
Concurrency bugs are notorious for changing their characteristics when you attempt to diagnose them, because they can be so sensitive to timings of events in your code.

You NEED a plan to add concurrency to a program.
Topic archived. No new replies allowed.