C++11 Thread without waiting

I am creating threads in a loop, but i dont want to wait until its finished. How do i do that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void XControl::OnClientConnect()
{
       // [...] other code

	for(;;)
	{
		if(sockConnection = accept(sockListen, (SOCKADDR*)&ADDRESS, &AddressSize))
		{
			int slot = GetFreeSlot();

			if(slot != -1)
			{
				c_Handle[slot] = new control_struct();
				c_Handle[slot]->cSock = sockConnection;

				std::thread thread(&XControl::ControlThread, this, slot);
                                // Loop continues here
			}
			else
			{
				sendasync(sockConnection, "Server is full");
			}
		}
	}
}


As you can see I cant wait for its execution because this code handles the incoming connections and it needs to go on.
With waiting i mean join()

(And please do not suggest using CreateThread(...))
Last edited on
threads will join in their destructor, which means the thread object must remain alive for as long as you want the thread open.

So making it local in an if() block is bad, because it goes out of scope as soon as the if() ends, which means the thread also ends.

You'll have to keep these threads at a larger scope.

1
2
3
4
5
6
7
8
9
10
11
12
// perhaps as a member of XControl?
typedef std::unique_ptr< std::thread >   threadptr;
std::vector< threadptr >  openThreads;


// then when you want to make threads...

for(...)
{
   if(...)
   {
      openThreads.push_back( threadptr( new std::thread(&XControl::ControlThread,this,slot) ) );
Last edited on
Thank you for this idea!

Works perfectly now.
Topic archived. No new replies allowed.