C++ Thread class

Introduction

With clang it will be:

clang++ -std=c++11 -Wall -pthread source.cpp 

Within a process, there can be multiple threads.

Threads or threads of execution are an OS mechanism that allows us to execute multiple pieces of code concurrently/simultaneously.

For example, we can execute multiple functions concurrently using threads.

A process can spawn one or more threads.

Threads share the same memory and thus can communicate with each other using this shared memory.

To create a thread object, we use the std::thread class template from a <thread> header file.

Once defined, the thread starts executing.

To create a thread that executes a code inside a function, we supply the function name to the thread constructor as a parameter.

Example:

#include <iostream> 
#include <thread> 

void function1() 
{ 
    for (int i = 0; i < 10; i++) 
    { /*www.ja  v a2  s  .  c  o m*/
        std::cout << "Executing function1." << '\n'; 
    } 
} 
int main() 
{ 
    std::thread t1{ function1 }; // create and start a thread 
    t1.join(); // wait for the t1 thread to finish 
} 

Here we have defined a thread called t1 that executes a function function1.

We supply the function name to the std::thread constructor as a first parameter.

In a way, our program now has a main thread, which is the main() function itself, and the t1 thread, which was created from the main thread.




PreviousNext

Related