Multithreading in C++ -Thread creations and basic functions in thread
Multithreading in C++
Thread
is a light weight process under execution. If multiple threads are running, it
need to manage memory, simultaneous threads. In c++, there is a header file
<thread> which supports multithreading.
How to create a thread?
A thread is created by the use of
std::thread class. The syntax is given below.
Syntax:
thread thread_name(callable);
here, thread_name is the object for the thread class.
‘callable’- it is a object for function object.
Eg:
- · This c++ program includes the header file bits/stdc++.h.
- · It creates a function func() with a thread message to display.
- · Next, a main() function is created with threat t calling a function func() and an object is created for thread as t.
- · The object t calls a function join() and display a message.
Code:
#include <bits/stdc++.h>
using namespace std;
void func() {
cout <<
"It is a message from the thread!" << endl;
}
int main() {
thread t(func);
t.join();
cout <<
"It is the Main thread.";
return 0;
}
Output:
It is a message from the thread!
It is the Main thread.
Thread functions:
The operations can be performed on threads are given below.
- Getting Thread ID – It thread_name.get_id();
- ‘join()’ – thread_name.join();
- Detaching thread -thread_name.detach();
Let us create c++ Program for illustrate the thread
functions.
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
void getid1() {
cout <<
"Thread1's ID: " << this_thread::get_id() <<
"\n";
}
void getid2() {
cout <<
"Thread2's ID: " << this_thread::get_id() <<
"\n";
}
int main() {
thread t1(getid1);
thread t2(getid2);
// let us Get
thread IDs
cout <<
"t1 ID: " << t1.get_id() << "\n";
cout <<
"t2 ID: " << t2.get_id() << "\n";
// let us Join the
thread1 if joinable
if (t1.joinable())
{
t1.join();
cout <<
"thread1 is joined\n";
}
// let us detach
the thread2
if (t2.joinable())
{
t2.detach();
cout <<
"thread2 is detached\n";
}
cout <<
"Main thread is sleeping for 5 seconds...\n";
this_thread::sleep_for(chrono::seconds(5));
cout <<
"Now,Main thread is awake after 5 seconds.\n";
return 0;
}
Output:
t1 ID: 134838204831424
t2 ID: 134838196438720
Thread2's ID: 134838196438720
Thread1's ID: 134838204831424
thread1 is joined
thread2 is detached
Main thread is sleeping for 5 seconds...
Now,Main thread is awake after 5 seconds.
Hope you understood the basics of multithreading and its operations in c++. The programs included in this blog helps you to know about thread creation and its functions usage. Keep Coding.
Comments
Post a Comment