Miscellaneous C++

Creating a Thread

Overview

In this video, we present a simple multi-threaded program. A thread is a line of execution. Having multiple threads allows multiple statements to be executed at the same time.

Download Code

Typically, short programs, like the one below, use only one thread that starts execution at the beginning of the main function. Such programs are relatively easy to trace through, in comparison to multi-threaded programs.

#include <iostream>

int main() {
    std::cout << "Hello World!" << std::endl;
    return 0;
}

Threads are an element of the operating system, and in this case we are writing programs for the Microsoft Windows operating system. So, we need to include the header file "windows.h" in our "main.cpp" file, as shown below.

The function that we use to make new threads is the function CreateThread(), which returns a handle to the newly created thread. This function takes several parameters. The parameters that we are most interested in are the thread function and the parameter that is passed into the thread function when it is called. The thread function has a void pointer as its sole argument, and this argument come via the fourth parameter of our CreateThread() function. In the case of this thread, its function is ThreadFn() and the parameter that is passed into it is a pointer to the unsigned int "uiCounter." Although we pass in a Thread ID parameter and get a value back, we will ignore it for the present lesson.

Our programs execution consists of two threads: one thread is created (the main thread) to begin executing our program in the main() function, and then the main thread creates the second thread, internally.

The second thread begins its execution in the function ThreadFn(). Most of the time, this threads remains in the internal loop that increments the counter variable. Internally, we refer to the counter "uiCounter" by the reference "uirCounter." Eventually, the counter reaches its maximum value and the thread exits the function.

At the same time the second thread is executing this loop, main thread is in a loop that outputs the value of the counter every time the "Enter" key is pressed. The longer the user waits between subsequent presses, the more the value of the counter increases. This is because the second thread is incrementing the counter at the same time the main thread is running this loop. The main thread leaves this loop when we enter 'q.' Then the main thread closes the handle to the thread—we will explain why this is done later.

 

© 2007–2024 XoaX.net LLC. All rights reserved.