Hanging by a Thread

In programming games we often come across situations where some code is very cpu heavy, i.e the code takes a long time to execute. This acts as a bottleneck and in turn stalls the execution of other critical parts of the same or a different program. One common example of this are pathfinding algorithms which are very expensive to run and so the only solution in this case is to run the pathfinding algorithms on a separate thread so that the remaining threads are free to do theire own thing.

WHAT IS A THREAD?

Multithreading is a feature of modern cpu’s that allows the concurrent execution of two or more parts of a program so that the cpu is utilized efficiently. Each part of such programs is called a thread. C++11 comes with multithreading support. The thread classes and the functions are defined in the header file <thread> and std::thread is the thread class.

HOW TO USE A THREAD?

We can start using a thread by creating an object of the type std::thread and passing in the callable function. In code it looks like this…

std::thread threadobj(callable)

Where callable could be…

  • A Function Pointer
  • A Function Object
  • A Lambda Expression

Today we are only going to see how we can run a function inside a thread. Below code is an example of running a function as a thread.

void demo_func(params)
{
 cout<<"Running demo func as a thread"<<endl;
}
void main()
{
 std::thread thread_obj(demo_func,parmas);
}

That’s it now the demo_func will run in it’s own thread and if it has cpu heavy calculations then they will no longer stall the main thread.

WAITING FOR THREAD TO FINISH

When a thread is running we often want to wait for the thread to finish its execution before running a piece of code. Suppose we are running a pathfinding algorithm then we will want the code to finish finding a path before running a code that depends on that path. We can wait for a thread to finish by using std::thread::join() function. In code this looks like this…

void demo_func(params)
{
 cout<<"Running demo func as a thread"<<endl;
}
void main()
{
 std::thread thread_obj(demo_func,parmas);
 thread_obj.join()
 cout<<"Thread has finished executing"<<endl;
}

The above code here will block the main thread and the “Thread has finished executing” line will only be printed once the thread has finished running.

That’s all for today folks, we will continue this series and talk more about threads in the near future. Hope this has been a gentle introduction. Cheers!

READ – CONNECT – BOOST – CREATE

Related :

Follow :