Creating C++ threads
Filed in: C++
In order to create threads in C++ using the C++11 standard you need to use a C++11 compatible compiler, for this demo I used gcc.
The first thing you need is to include the header
Next you need to decide if you want the threaded code to run from a function, a Callable ie operator() method or a Lambda.
Here is an example of a function where I pass in a String for the function to use:
{
std::cout<<"Hello Concurrent World " << s << '\n';
}
//From main we can then run
//Run a pointer to a function as a thread
std::thread t = std::thread(hello,"Passed_string");
t.join(); // join main tread to this thread so it can finish its work
Note how the join() is called on the thread so we can attach it to Main thread so main will not terminate until this thread has run.
If you want to call a Callable operator in a class you would first create the class overriding () operator and then run the thread like so:
{
public:
//callabe operator
void operator()() const
{
std::this_thread::sleep_for(std::chrono::milliseconds(2000) );
std::cout << "Howdy from thread" <<'\n';
}
};
//From main
//Run a callable Class as a Thread, create thread using function objects
std::thread *callable_thread=new std::thread{background_task()};
callable_thread->join(); // join main tread to this thread so it can finish its work
The class here is background_task that runs the task in the () method. It also demonstrates how to sleep inside a thread.
The last way to run a thread in C++ is by using a lambda which is just some on the fly code. To do this we pass the lambda to thread.
std::thread my_lambda([]{
std::cout << "Hello from my Lambda " << '\n';
});
my_lambda.detach(); //detach so we are not dependant on this thread - this makes it a daemon
Note here we are using the detach method to spawn this off as a separate thread, or what we would call a daemon thread, that is the thread is not bound by the current thread that calls this lambda thread. In this example it is trivial because we shut down straight after calling the lambda
now putting it altogether we have an entire cpp file with all of these examples in it
// cppthreads.cpp
// c++Test
//
// Created by ARIF JAFFER
// Copyright © 2020 ARIF JAFFER. All rights reserved.
//
#include ≺stdio.h>
#include ≺iostream>
#include ≺thread>
#include ≺chrono>
void hello(std::string const& s)
{
std::cout<<"Hello Concurrent World " << s << '\n';
}
class background_task
{
public:
//callabe operator
void operator()() const
{
std::this_thread::sleep_for(std::chrono::milliseconds(2000) );
std::cout << "Howdy from thread" <<'\n';
}
};
int main()
{
//How many threads can I run on this system at the same time
std::cout << "Concurrency level " << std::thread::hardware_concurrency() << '\n';
//Run a pointer to a function as a thread
std::thread t = std::thread(hello,"Passed_string");
t.join(); // join main tread to this thread so it can finish its work
//Run a callable Class as a Thread, create thread using function objects
std::thread *callable_thread=new std::thread{background_task()};
callable_thread->join(); // join main tread to this thread so it can finish its work
//Run a Thread using a lambda
std::thread my_lambda([]{
std::cout << "Hello from my Lambda " << '\n';
});
my_lambda.detach(); //detach so we are not dependant on this thread - this makes it a daemon
//Needed to give the lmbda thread time to complete.
std::this_thread::sleep_for(std::chrono::milliseconds(2000) );
delete callable_thread;
return 0;
}
C++ Mutex and Preventing race conditions
Low Latency Java using CAS and LongAdder
Naive Bayes classification AI algorithm
K-Means Clustering AI algorithm
Equity Derivatives tutorial
Fixed Income tutorial
Java
python
Scala
Investment Banking tutorials
HOME

The first thing you need is to include the header
#include ≺thread>
Next you need to decide if you want the threaded code to run from a function, a Callable ie operator() method or a Lambda.
Here is an example of a function where I pass in a String for the function to use:
void hello(std::string const& s)
{
std::cout<<"Hello Concurrent World " << s << '\n';
}
//From main we can then run
//Run a pointer to a function as a thread
std::thread t = std::thread(hello,"Passed_string");
t.join(); // join main tread to this thread so it can finish its work
Note how the join() is called on the thread so we can attach it to Main thread so main will not terminate until this thread has run.
If you want to call a Callable operator in a class you would first create the class overriding () operator and then run the thread like so:
class background_task
{
public:
//callabe operator
void operator()() const
{
std::this_thread::sleep_for(std::chrono::milliseconds(2000) );
std::cout << "Howdy from thread" <<'\n';
}
};
//From main
//Run a callable Class as a Thread, create thread using function objects
std::thread *callable_thread=new std::thread{background_task()};
callable_thread->join(); // join main tread to this thread so it can finish its work
The class here is background_task that runs the task in the () method. It also demonstrates how to sleep inside a thread.
The last way to run a thread in C++ is by using a lambda which is just some on the fly code. To do this we pass the lambda to thread.
//Run a Thread using a lambda
std::thread my_lambda([]{
std::cout << "Hello from my Lambda " << '\n';
});
my_lambda.detach(); //detach so we are not dependant on this thread - this makes it a daemon
Note here we are using the detach method to spawn this off as a separate thread, or what we would call a daemon thread, that is the thread is not bound by the current thread that calls this lambda thread. In this example it is trivial because we shut down straight after calling the lambda
now putting it altogether we have an entire cpp file with all of these examples in it
//
// cppthreads.cpp
// c++Test
//
// Created by ARIF JAFFER
// Copyright © 2020 ARIF JAFFER. All rights reserved.
//
#include ≺stdio.h>
#include ≺iostream>
#include ≺thread>
#include ≺chrono>
void hello(std::string const& s)
{
std::cout<<"Hello Concurrent World " << s << '\n';
}
class background_task
{
public:
//callabe operator
void operator()() const
{
std::this_thread::sleep_for(std::chrono::milliseconds(2000) );
std::cout << "Howdy from thread" <<'\n';
}
};
int main()
{
//How many threads can I run on this system at the same time
std::cout << "Concurrency level " << std::thread::hardware_concurrency() << '\n';
//Run a pointer to a function as a thread
std::thread t = std::thread(hello,"Passed_string");
t.join(); // join main tread to this thread so it can finish its work
//Run a callable Class as a Thread, create thread using function objects
std::thread *callable_thread=new std::thread{background_task()};
callable_thread->join(); // join main tread to this thread so it can finish its work
//Run a Thread using a lambda
std::thread my_lambda([]{
std::cout << "Hello from my Lambda " << '\n';
});
my_lambda.detach(); //detach so we are not dependant on this thread - this makes it a daemon
//Needed to give the lmbda thread time to complete.
std::this_thread::sleep_for(std::chrono::milliseconds(2000) );
delete callable_thread;
return 0;
}
People who enjoyed this article also enjoyed the following:
C++ Mutex and Preventing race conditions
Low Latency Java using CAS and LongAdder
Naive Bayes classification AI algorithm
K-Means Clustering AI algorithm
Equity Derivatives tutorial
Fixed Income tutorial
And the following Trails:
C++Java
python
Scala
Investment Banking tutorials
HOME
