Can someone post a simple example of starting two (Object Oriented) threads in C++.
I'm looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library.
I left out any OS specific requests in the hopes that whoever replied would reply with cross platform libraries to use. I'm just making that explicit now.
Thread is often referred to as a lightweight process. The process can be split down into so many threads. For example, in a browser, many tabs can be viewed as threads. MS Word uses many threads - formatting text from one thread, processing input from another thread, etc.
A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. C does not contain any built-in support for multithreaded applications.
I was recently reading "The C Programming language" by Ritchie, I noticed that C is a single threaded language.
For example, a desktop application providing functionality like editing, printing, etc. is a multithreaded application. In this application, as printing is a background process, we can perform editing documents and printing documents concurrently by assigning these functions to two different threads.
Create a function that you want the thread to execute, eg:
void task1(std::string msg) { std::cout << "task1 says: " << msg; }
Now create the thread
object that will ultimately invoke the function above like so:
std::thread t1(task1, "Hello");
(You need to #include <thread>
to access the std::thread
class)
The constructor's arguments are the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.
If later on you want to wait for the thread to be done executing the function, call:
t1.join();
(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution).
#include <string> #include <iostream> #include <thread> using namespace std; // The function we want to execute on the new thread. void task1(string msg) { cout << "task1 says: " << msg; } int main() { // Constructs the new thread and runs it. Does not block execution. thread t1(task1, "Hello"); // Do other things... // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution. t1.join(); }
More information about std::thread here
-std=c++0x -pthread
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With