C++ Multithreading: Understanding Threads

Share the Article

C++ Multithreading is a powerful feature. This article explains the entire concept behind this concept.

Why Threads ?

Threads are mainly required for doing multiple jobs at one time without waiting for one job to complete.

For example, we have an application which need to perform multiple jobs as below –

  • Taking input from keyboard.
  • Formatting of data
  • Displaying Data on Screen.

Single Threaded and Multi Threaded Applications

Single Threaded Application will perform all above jobs in serial manner . Firstly, it will take input from user .Secondly, it will format data .Thirdly , it will Display data. One job need to wait for other jobs .

But in case of Multiple threaded application we can dedicate one thread for each job. Therefore, all jobs shall execute in parallel. For each job, we shall create following threads in C++ program.

  • Input thread -whose job is to take input from Keyboard and give to formatter thread.
  • Formatter thread – take Data from input thread and format it and give to Display thread.
  • Display thread – on receiving data display it to the screen.

So with C++ Multithreaded approach for above application we have increased the overall efficiency of the above application by introducing threads for doing jobs in efficient manner .In above example we have given each thread a dedicated responsibility so that overall job can be completed fast.

Threads included in below Header file

#include <thread>

How to compile the code which uses C++ Multithreading

For compiling main.cpp for C++ Multithread need to include -pthread options with g++

g++ -std=c++11 -pthread main.cpp -o main.out

Basic example with just single thread

Below example is demonstrating an application in which we have created a single thread.

First Step:

Firstly, we need to create an object job of std::thread class. To this (job) thread object, a function performtask( ) is attached. This function embeds the responsibility of job thread. This statement shall automatically start execution of job thread in parallel to main program thread.

Second Step:

To ensure that the main program thread shall wait for job thread to finish its task, the program must call the thread function job.join( ). If we do not call job.join() main thread shall exit without waiting for job thread.

#include<thread> //for threads #include<iostream> //main header using namespace std;//for namespace void performTask() { cout<<"performTask"<<endl; } int main() { std::thread job( performTask); job.join(); cout<<"Main job done"<<endl; }

The output of above application will be

Basic example of c++ threads

Passing Function arguments in thread

Below example is demonstrating same basic application where we have created a single thread but now also pass parameter from main thread.

#include<thread> //for threads #include<iostream>//main header using namespace std;//for namespace void performtask(int jobInt,char jobChar) { cout<<"parameter int "<<jobInt<< endl; cout<<" parameter char " <<jobChar<<endl; } int main() { int jobInput =3; char jobChar ='c'; std::thread job(performtask,jobInput,jobChar); job.join(); cout<<" Main job done"<<endl; }

The output of above application will be

Passing arguments with C++ thread

C++ Multithreading example: Starting multiple threads together

Below example is demonstrating an application where we have created multiple threads and also passed parameters from main thread. In below application we can see that multiple threads are active and performing their jobs together . No thread is waiting for other to perform job.

#include<thread> //for threads #include<iostream> //main header using namespace std;//for namespace void performTask(int value) { for(int i =0;i<5;i++) { cout<<"performTask" <<value << endl; } } int main() { std::thread job1(performTask,1); std::thread job2(performTask,2); std::thread job3(performTask,3); job1.join(); job2.join(); job3.join(); cout<<"Main job done"<<endl; }

Output

C++ threads with multiple threads in  execution

Detaching a thread from the main thread (program)

Thread detach feature mainly detaches a main thread object from thread in execution .The moment we called detach on thread object, this thread execution becomes independent.

For example , if we want to create a background thread which should keep running even when the main program exits. In such case, we shall call detach on thread object.

The following example demonstrates such application where we have created a thread object showdata and then we have called detach on this thread.

#include<thread> //for thread #include<iostream>//main header #include<chrono> //for date time using namespace std; void processData() { while(1) { cout<<"Hi MainFunda!"<<endl; std::this_thread::sleep_for (std::chrono::seconds(1)); } } int main() { std::thread showData(processData); showData.detach(); cout<<"Main exited" << endl; }

Output

Using  threads with detach

C++ Multithreading: Joinable Threads

Thread join is mainly used if one thread wants to wait for other thread. For example, thread t1 want to wait for thread t2 to exit before doing some task t1 need to call t2.join( ) .

In below example main thread want to wait for t1 thread to finish its job. Therefore, code in main thread shall call t1.join( ).

#include<thread> //for threads #include<iostream>//main header #include<chrono> //for date time using namespace std; //for namespace void show() { int count = 0; while(count++<5) { cout<<"Main Funda"<<endl; std::this_thread::sleep_for (std::chrono::seconds(1)); } } int main() { std::thread t1(show); t1.join(); cout<<"Main job Done"<<endl; }

The Output of below programme will be

Using threads with join function call

What if the thread already exited before join

It may happen that t1 has already exited or t1 doesn’t have any thread associated with it in this case program shall terminate .

#include<thread> //for threads #include<iostream> //main header #include<chrono> //for date time using namespace std; //for namespace void show() { cout<<"Main Funda"<<endl; std::this_thread::sleep_for (std::chrono::seconds(1)); } int main() { std::thread t1(show); t1.join(); t1.join(); //program will crash cout<<"main exited"<<endl; }

Output

threads join function throws an exception

Remedy – joinable( ) check

In order to save program from crash we can check the thread using joinable function.

#include<thread> //for threads #include<iostream> //main header #include<chrono> //for date time using namespace std; //for namespace void show() { cout<<"Main Funda"<<endl; std::this_thread::sleep_for (std::chrono::seconds(1)); } int main() { std::thread t1(show); t1.join(); if(t1.joinable()) { t1.join(); //program will not crash } cout<<"main exited"<<endl; }

Output

Using threads with joinable check

Threads Synchronization – Race Conditions

Thread synchronization is mainly used for avoiding race conditions between threads. Race condition mainly occurred if 2 or more threads want to operate on same data or resources.

For example, We have one thread for updating global data and other thread for reading global data. Due to multiple access of global data at same time with multiple threads can corrupt the data. Therefore, we need to synchronize threads while accessing same data or resource so let one thread finish updating then only other thread read data. In order to synchronize data in C++ we have several mechanism such as

  • Mutex,
  • Condition Variables
  • Semaphores etc.

Below we have discussed some mechanism.

Thread – Example for Mutex

For instance , we have data or shared resource that we want to access from multiple threads. For data protection mutex is ideal option for us to synchronize threads . Thread need to lock and unlock mutex during access of shared data or resource.

Header File
#include<mutex>

Assume the Scenario

We can take an application which is having a stack object as shared resource. This resource needs access from 2 threads doing below jobs-

  1. job of 1st thread is to push item 10 in to stack for 5 times.
  2. job of 2nd thread is to push item 20 in to stack for 5 times.
  3. After both threads are done, then main thread needs to print content of stack.

We need to guard the stack so that threads should not corrupt stack

(one thread can override other so that total element is less than 10).

#include <iostream> //main header #include <thread> //for thread #include <mutex> //for mutex #include<stack> //for stack using namespace std; //for namespace std::mutex stacklock; //MUTEX std::stack<int> s1; //Common Resource void pushData (int n) { stacklock.lock(); //MUTEX lock for (int i=0; i<5; ++i) { s1.push(n); } stacklock.unlock(); //MUTEX unlock } int main () { std::thread stackpush1 (pushData,10); std::thread stackpush2 (pushData,20); stackpush1.join(); stackpush2.join(); while(!s1.empty()) { cout<<s1.top()<< " "; s1.pop(); } cout << endl; return 0; }

The output of above application will be all 10 and 20’s together .No corruption

Using threads with mutex

Threads – Example for Condition Variable

For example , we have condition where one thread need to wait for other thread for doing its job .In this case we need to use condition variable for synchronizing threads . A condition variable always linked to mutex.

Let us take an example where we have 2 threads one thread in incrementing value of shared variable by 5 and other thread need to display updated value .So displaythread need to wait for incrementing thread. In order to solve this problem we can take help for condition variable as demonstrated below

#include <iostream> //main header #include <thread> //for thread #include <mutex> //for mutex #include <condition_variable> //for condition variable #include<chrono> //for date time using namespace std; //for namespace std::mutex mvalue; std::condition_variable condvariable; int value = 0; void incrementvalue() { std::this_thread::sleep_for (std::chrono::seconds(1)); std::lock_guard<std::mutex> lock(mvalue); value = value +5; cout<<"increment Thread Notify Display thread"<<endl; condvariable.notify_one(); } void displayValue () { cout<<"Display thread waiting"<<endl; std::unique_lock<std::mutex> lock(mvalue); cout<<"Display thread waiting mutex"<<endl; condvariable.wait(lock); std::cout << "Value after Incrementing" << value << endl; } int main () { std::thread displayThread(displayValue); std::thread incrementThread(incrementvalue); incrementThread.join(); displayThread.join(); cout<< "Main job done"<<endl; return 0; }

The output of above application will be

thread example with condition variable

Main Funda: C++ Multithreading is a very powerful feature but needs proper synchronization mechanism.

Related Topics:

Lambda in C++11
Lambda in C++17
What are the drawbacks of using enum ?
Which member functions are generated by compiler in class?
How to stop compiler from generating special member functions?
Compiler Generated Destructor is always non-virtual
How to make a class object un-copyable?
Why virtual functions should not be called in constructor & destructor ?
Explaining C++ casts
How pointer to class members are different ?
How std::forward( ) works?
Rule of Three
How std::move() function works?
What is reference collapsing?
How delete keyword can be used to filter polymorphism
emplace_back vs push_back

Share the Article

1,305 thoughts on “C++ Multithreading: Understanding Threads

  1. . Odbiór w domu apeldoorn lingam massage belgium sex date south holland dziewczyna zostaje wyruchana więc co za gówno tanie prostytutki zwroty walencja prostytutek prive sex nijmegen sex darmowy czat definicja synonimów autonomicznych prostytutek dla dzieci senoritas dziwki zawiadomienia o usługach seksualnych Pieprzę moją sukę suko suko transseksualiści ogłoszenia włochy galarate dating board amatorskie zdjęcie dziwki gdzie znaleźć dziwki w paryżu. Pokaż na żywo najwięcej culon minaj à trois cont kontakty hommes caracas amatorska dziwka barcella bez majtek Facebook masaż nuru seks oralny w pobliżu meppel trochę rygorystyczny afrykański rogaty w pobliżu alcobendas puttan mapa eur rzym czat aby poznać nowych ludzi. , Busty prysznic cudzołóstwa w pobliżu san cristobal de la laguna masaż erotyczny wykonany przez mężczyzn sex shat stara zdzirowata lekarka uwielbia kutasy https://cutemesh.com/community/profile/loviehenn177281/ Rozgrywka w Dread Hunger rozpoczyna się od rozdania pokerowego, a gra odbywa się na zasadach 5 card draw (poker pięciokartowy dobierany). W momencie okazania kart wygrywa Gracz, który posiada najsilniejszy układ kart. To jedna z najczęstszych pomyłek. Kolor, czyli pięć kart tego samego koloru, zawsze bije strita, czyli pięć kart w kolejności numerycznej. Poker, który jest układem składającym się z pięciu kolejnych kart jednego koloru, bije oba te układy.  Kiedy dwóch graczy otrzyma wspomniane powyżej dwie karty własne, rozpoczyna się faza preflop. Każdy z graczy patrzy w swoje karty i decyduje jaką decyzję podjąć. Akcja przebiega zgodnie z ruchem wskazówek zegara począwszy od gracza na lewo od big blinda. Gracz ma trzy opcje, spasować, sprawdzić lub podbić. Następnie akcja przesuwa się do kolejnego gracza i tak aż do momentu, gdy każdy z chętnych do pozostania w rozdaniu graczy umieści jednakową ilość żetonów. Wówczas wykładany jest flop, czyli trzy karty wspólne widoczne dla wszystkich graczy przy stole.

  2. Some truly fantastic articles on this website, appreciate it for contribution. “Once, power was considered a masculine attribute. In fact, power has no sex.” by Katharine Graham.

  3. Before proceeding, we’ll need to confirm you’re of legal age in your province of residence. Lastly, I would recommend that pharmacists start to think of cannabis as similar to but different from any other medication they have ever seen. There are hundreds of strains of medical cannabis in Canada, each of which lead to slightly different responses. There will never be an SPC for cannabis use, so there are many unknowns regarding efficacy, safety, drug interactions, dosing, monitoring, methods of administration and contraindications. You must be comfortable with addressing patient concerns and questions, even when you may not have a perfect answer. The current regime for medical cannabis will continue to allow access to cannabis for people who have the authorization of their healthcare provider. https://rafaelhxlz987531.blogozz.com/14661900/adhd-medical-marijuana Here is our list of the best online Cannabis websites in Canada that sell cannabis and cannabis related products, delivered straight to your door. You will also find how well each online retailer is rated by past and present customers. Being one of the industry’s trailblazers, we strive to uphold our reputation as the best marijuana dispensary in Canada. We have over 5000 glowing reviews around the web, from each Canadian province. Whenever there’s something wrong with your order, we do our best to solve the problem because your satisfaction is our top priority. You can find more reviews from sites such as CannabisOntario.net, WeedList.org, and BCWeedDelivery.org. For those of you who are new to the cannabis community, you may be wondering how and why cannabis helps boost creativity – and we are here to break that down. And those experienced cannabis consumers, we have narrowed down the best list of creative boosting cannabis strains!

  4. But how do I start a game? Easy Poker lives up to its name while offering a hassle-free experience. Once a player installs the application, they can easily create a new poker table with one tap. Then, they would need to share a 4-digit code with their friends they want to play with. The receiving party needs to select the “Find Game” button and type in the unique 4-digit code in order to join the private poker table. And that’s it. No need to buy chips or go through extra settings. The game allows you to play with friends and allow you to play with friends. It is a simple game where you can interact with chips and cards. It is an amazing experience for all competitors. This is one of the best free multiplayer poker games that gets you up and close with thousands of real poker players where you can get into an amazing competition and prove your skills. You need to put your Poker skills to work and become a poker professional. You start as a rookie and make your way to the VIP level. You can invite your friends to the game and make some new friends and enjoy playing poker with them. https://lanevmap643198.bloggadores.com/14717736/miami-dice-casino-recension While cryptocurrency is still a long way from being accepted as a mainstream form of payment, some online casinos are experimenting with using it as a form of payment. Crypto Casino Sites are driven by the benefits and advantages of Bitcoin and Ethereum, such as lightning-fast transaction speeds and improved security. There is no compromise on the quality of service or games, as leading software developers are on hand to create epic video slots and other casino content, which is on a par with what players will experience with more traditional services. Content at crypto casinos can look quite different to that you would normally see at a traditional online casino. Multiplayer ‘crash’ and ‘dice’ games are particularly popular, while slots can sometimes take a backseat. User anonymity: Traditional casinos require their patrons to provide personal details to set up an account or cash out their winnings, which extends to many online gambling platforms. In contrast, gambling dApps keep your information private by associating your network activity with a transaction address composed of a string of random alphanumeric characters. This enhanced level of anonymity allows users to transact on these dApps without revealing their identity.

  5. Milliyet. Sayfa 1. Bako davası mahkeme başkam “İki partinin kuıbanı oldum” HÂKİM savunmada
    0 Banker Bako’dan rüşvet alarak beraat kararı verdiği iddiasıyla
    hakkında 10 yıl hapis istemiyle dava açılan İstanbul 7.Ağır Cez.

    Haberi Oku Sayfayı Oku. Milliyet.

  6. Link exchange is nothing else but it is simply placing the other person’s webpage link on your
    page at suitable place and other person will also do similar in favor of you.

  7. En yeni +18 filmleri sizler için özele seçip
    paylaşarak heyecanınıza ortak olmaktayız. Konulu seks filmlerin her birini donmadan kaliteli bir şekilde
    izleyebileceğiniz bir atmosfer oluşturarak, siz değerli
    ziyaretçilerimize üst kalitede bir türkçe filmi sex
    izleme hizmet sunmaktayız. Yeşilçam Sex Filmleri.

  8. As I am looking at your writing, 하노이 VIP마사지 I regret being unable to do outdoor activities due to Corona 19, and I miss my old daily life. If you also miss the daily life of those days, would you please visit my site once? My site is a site where I post about photos and daily life when I was free.

  9. It’s the best time to make some plans for the future and it’s time to be happy.
    I have read this post and if I could I wish to suggest you few interesting things or tips.

    Perhaps you can write next articles referring to this article.
    I wish to read more things about it!

  10. You’re so awesome! I do not suppose I’ve read anything like this before.
    So good to discover somebody with unique thoughts
    on this subject. Seriously.. many thanks for starting this up.
    This site is one thing that’s needed on the internet, someone with a little originality!

    My site: coupon

  11. [url=http://smotret-film-prosmotr-filmov.ru/map3429.html]Неприкасаемые 1987 фильм смотреть онлайн [/url] Смотреть фильм онлайн бесплатно лангольеры http://smotret-film-prosmotr-filmov.ru/map3430.html

  12. Howdy, i read your blog from time to time and i own a similar
    one and i was just wondering if you get a lot of spam feedback?
    If so how do you reduce it, any plugin or anything you
    can suggest? I get so much lately it’s driving me insane so any support
    is very much appreciated.

  13. Da alles elektronisch abläuft gibt es von Seiten der Spieler einige Vorurteile im Bezug auf Chancen und Fairness. Allerdings werden die Online Casinos natürlich auch kontrolliert. Sollte ein Betrugsfall öffentlich werden, würde der Ruf des Casinos in unserer heutigen schnellen Informationswelt sofort an Wert verlieren. Außerdem sind die Auszahlungsquoten und somit auch die Chancen der Spieler höher im Vergleich zu den echten Casinos. Der Grund dafür sind die geringeren Unterhaltungskosten eines Online Kasino. Es müssen zum Beispiel weniger Personal- und Gebäudekosten bezahlt werden. Dieses gesparte Geld wird deshalb durch eine höhere Auszahlungsquote an den Spieler zurückgegeben. Geschäfte haben meistens Öffnungszeiten, so auch ladengestützte Casinos. Diejenigen, deren Arbeitszeiten sich nicht mit denen von Casinos vereinbaren lassen, hatten früher einfach Pech. Online-Casinos allerdings kennen keine Öffnungszeiten, da sie nicht an einen Ort gebunden sind und damit auch unabhängig von der Zeit sind. 24 7 steht es Spielern also frei, im Online-Casino zu Spielen.  https://indigopsychics.com/community/profile/joelcansler482/ Alle Kombinationen sind beim Pokern möglich: Es können eine, keine oder beide Hole-Cards verwendet werden. Die Bewertung des Blattes erfolgt auf Basis der folgenden Reihenfolge, die du unbedingt auswendig lernen solltest, um auch in hitzigen Poker-Duellen einen kühlen Kopf bewahren zu können: Das Ziel von Texas Hold’em ist es, die höchste Poker-Kombination zu erzielen und die Gegner mit dem Kartenblatt zu schlagen. Hinweise zum Showdown beim Texas Holdem► In den meisten Casinos gilt, dass derjenige Spieler, der als letzter gesetzt oder erhöht hat, als erster seine Karten aufdecken muss.► Kein Spieler ist verpflichtet, keine Karten aufzudecken. Man kann auch aufgeben und seine Karten abwerfen, wenn man verloren hat und seine Hand nicht preisgeben will.► Haben zwei oder mehr Spieler die gleiche Hand (was beim Texas Holdem durchaus ab und zu vorkommt), wird der Pot zu gleichen Teilen unter diesen Spielern geteilt.

  14. I don’t even know how I ended up here, but I thought this
    post was great. I do not know who you are but definitely you’re going to a
    famous blogger if you are not already 😉 Cheers!

  15. Greetings! I know this is somewhat off topic but I was wondering if you knew where I could get a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having trouble
    finding one? Thanks a lot!

  16. Link exchange is nothing else but it is simply placing the
    other person’s weblog link on your page at appropriate place and other person will also do similar for you.

  17. Fantastic goods from you, man. I have bear in mind
    your stuff prior to and you are just too fantastic. I really like what you have got
    here, really like what you’re saying and the way during which
    you are saying it. You’re making it enjoyable and you continue to
    take care of to stay it sensible. I cant wait to learn much more from you.
    That is actually a tremendous website.

  18. Thank you a lot for sharing this with all folks you actually recognize what you are talking approximately!
    Bookmarked. Please additionally seek advice from my website =).
    We will have a link trade contract between us

  19. Im folgenden Artikel geht es um die besten Tipps für Lotto Österreich 2022. Um die Tickets beim Lottospielen auf die beste Art und Weise zu nutzen, gilt es, einige wichtige Tipps zu beachten. Natürlich ist es nicht einfach, gleich von Anfang alle Tricks zu kennen und alles über die unterschiedlichen Lottospiele zu wissen – hier helfen wir nach! 6 aus 45 – Aber wie kommt man zum Sechser? Und was passiert eigentlich danach, wenn ein Lotto-Jackpot geknackt wurde? Wir haben bei den Österreichischen Lotterien direkt nachgefragt. What is value added tax with example? Wenn du jede Woche Lotto spielst, ist die Wahrscheinlichkeit zu gewinnen größer, als wenn du nur einmal alle Jubeljahre einen Tippschein abgibst, vielleicht in unserem beliebten LOTTO 6 aus 45. Es ist nicht weiter erstaunlich, dass wir sehr oft von Gewinnern hören, die ein Abo für ihre Lieblingslotterie im Lottoland abgeschlossen haben. Wichtig ist aber vor allem, das Tippen zu genießen, nicht die Hoffnung zu verlieren und davon zu träumen, was du mit einem Lotto-Gewinn anfangen würdest! https://xrchippenham.earth/forum/community/profile/lelagaunt48148/ Sowohl die William Hill Casino App, als auch der Sportwetten-Bereich oder sogar das gesamte Portal können von einer Störung betroffen sein. Eventuell findet ein Update statt. Oder die Server sind schlicht und ergreifend überlastet. Dann gilt es zu warten. Dauert es länger, ist der Support zu kontaktieren. In jedem Fall lohnt es sich bei einem alternativen Buchmacher angemeldet zu sein – diesbezüglich können wir auch die Sunnyplayer App empfehlen. Hier sind die TOP Online Slot Spiele, Tischspiele und Jackpot-Slots von höchster Qualität. Jackpot-Jäger werden sich freuen, da William Hill Casino eine fantastische Auswahl an progressiven Jackpot-Slots bietet. Video Poker – Spieler können Variationen von All American, Deuces Wild, Joker Wild und Jacks or Better ausprobieren. Kartenspiele-Fans werden in William Hill Casino ein großzügiges Angebot an Tischspielen finden. Dazu gehören die beliebtesten Titel der Zocker: Blackjack, Poker und Baccarat.

  20. Thanks, man. Yeah, I’m amazed by the feedback the post has received. Amazed and happy
    Wouldn’t it be great if there WAS a great promotion strategy that didn’t take time or money

  21. I’m no longer positive the place you”re getting your info, but great topic. I needs to spend some time learning much more or understanding more. Thank you for great information I used to be on the lookout for this information for my mission
    Take a look at my homepage – https://main7.net/aria/

  22. I’d like to thank you for the efforts you’ve put in penning this
    blog. I really hope to check out the same high-grade blog posts from you in the future as well.

    In truth, your creative writing abilities has motivated me to get my very own blog now 😉