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

3,256 thoughts on “C++ Multithreading: Understanding Threads

  1. At Refinery29, we’re here to help you navigate this overwhelming world of stuff. All of our market picks are independently selected and curated by the editorial team. If you buy something we link to on our site, Refinery29 may earn commission. Bringing these looks to the large audience of an HBO show may have given a sort of permission to others who wanted to experiment, she said. Comparatively, while runway makeup is often experimental, it can feel out of reach. “These characters “they fuck up, they make mistakes, they fall in love, they cry. They’re funny. They’re real. So it’s kind of inviting and refreshing to see cool makeup on TV,” she said. There’s no denying the huge influence that the hit show Euphoria has on current trends. Many people copy the show’s quirky makeup, the 90s2000s-inspired items, and the daring styles to breathe new life into their looks. Jules’ outfits are noteworthy for their magical girl sweetness – follow our styling tips above to emulate her ultrafeminine style! https://caidenmesh310864.blog-kids.com/14695225/nyx-eyebrow-gel-glue What do you get when you combine the benefits of toner and serum in one? This universal game-changer snatches pores and dark spots, and has a unique thick texture we bet you haven’t felt before—it’s Rihanna’s fave step in her routine for a reason. Over one week: Like we mentioned above, the Fenty Skin collection is all about simplicity. That’s why the brand offers multi-tasking products, like Fenty Skin Fat Water, a 2-in-1 serum combo. Despite its thick texture, it absorbs into the skin quickly and helps to reduce excess oil and shine thanks to the high concentration of witch hazel (a natural astringent). The formula also contains niacinamide, a multi-tasking ingredient that helps to strengthen the skin barrier, prevent acne, brighten skin tone, reduce signs of aging, and more.

  2. timolol intramuscular injection depo medrol For each day the government is shut down, more than 8 million in economic activity at our nation s hotels will be lost, putting jobs at risk and causing repercussions across many other related sectors, says Katherine Lugar, president and CEO of the American Hotel and Lodging Association, in an interview with Lodging Magazine clomiphene for men side effects

  3. How do I get my man to be more open
    Erectile dysfunction is one of the men’s progenitive trim disorders. It is cognized as an unfitness of men to attain erection during procreant intercourse to if they are sexually excited. Other symptoms of ED are, either it remains championing a dumpy while or does not occur at all. It is a repeated process. Erectile dysfunction is also called a type of impotence. Frailty is a wide light and covers scads other men’s health sexual disorders like- untimely ejaculation, be deficient in of sexual longing, и так далее Erectile dysfunction does not involve these problems. All these problems mutual to Erectile dysfunction can be cured with the help of can i buy generic viagra in canada and other real viagra pills online medicines.

    Causes
    Erectile dysfunction does not hold any specific cause. There are uncountable reasons behind its occurrence. It can be- true reasons, your healthfulness problems, medicines you are delightful, heated reasons, и так далее Give permission’s possess a look on ED causes in particular. Erectile dysfunction causes are- consequential blood stress, diabetes, favourable blood cholesterol, grit diseases (Parkinson’s illness and multiple sclerosis), surgery, low hormone levels, lifestyle factors (smoking and drinking) and others (stress, anxiety, a case of the jitters, misgivings, cavity). Aging factors also supervise to ED, but aging in itself is not a cause. Bellow testosterone levels also in some cases prompt to erectile dysfunction. Side effects caused by medications also net men unqualified in compensation erection.

    But there is nothing to trouble close to as treatments are available for ED. A specific such ready treatment proper for ED is can you buy viagra in canada over the counter.

  4. Se você está pensando em adquirir Bitcoins e outras criptomoedas, entenda por que o Mercado Pago é a melhor opção: Outro fator que justifica a alta segundo ele é a escassez no mercado. O bitcoin, por exemplo, tem apenas 21 milhões de unidades e é um ativo deflacionário. “Teremos uma onda explosiva de alta devido à escassez que tem surgido no mercado. Tanto bitcoin como ethereum e, em um segundo momento, a DOT irão ter uma forte explosão. No caso do Bitcoin, observamos uma pressão nos preços devido a menor oferta e maior demanda. Há um movimento de pessoas sacando nas corretoras e guardando bitcoins em suas wallets, o que diminui mais ainda a oferta deixando a moeda mais restrita, o que sobe o preço”, finaliza.  Entrega os produtos dentro do prazo *Texto atualizado às 15h30 para corrigir informações fornecidas pela equipe do Mercado Pago https://asug.cl/foro/profile/waylonbagshaw31/ Quando você pensa em como ganhar dinheiro com criptomoedas, certamente o primeiro nome que vem à cabeça é o Bitcoin. Entretanto, existem aproximadamente 20 mil moedas digitais além dele. Algumas dessas moedas são bem populares, muito comercializadas nas exchanges e aceitas como forma de pagamento em várias empresas no mundo inteiro. Vale lembrar que cada site leva em consideração uma fonte de conversão diária, semanal ou mensal, o que pode criar divergências em alguns valores. Verifique sempre em mais de um deles, para garantir. O que é evidente é que embora alguns membros da comunidade financeira tenham mantido o seu ceticismo, a Bitcoin tem tido um desempenho superior ao do mercado de ações e das principais comodidades a longo prazo. O valor da Bitcoin continua a subir hoje em dia.

  5. How do you attract a man emotionally
    Erectile dysfunction is one of the men’s sexual trim disorders. It is cognized as an ineptness of men to attain erection during procreant intercourse even if they are sexually excited. Other symptoms of ED are, either it remains after a transitory while or does not occur at all. It is a repeated process. Erectile dysfunction is also called a classification of impotence. Impotence is a encyclopaedic aspect and covers many other men’s haleness reproductive disorders like- unripe ejaculation, need of fleshly pine, и так далее Erectile dysfunction does not contain these problems. All these problems mutual to Erectile dysfunction can be cured with the helpers of viagra online buy and other viagra pills for men price medicines.

    Causes
    Erectile dysfunction does not have any circumscribed cause. There are many reasons behind its occurrence. It can be- medic reasons, your health problems, medicines you are taking, nervous reasons, и так далее Give permission’s have a look on ED causes in particular. Erectile dysfunction causes are- momentous blood compression, diabetes, loaded blood cholesterol, nerve diseases (Parkinson’s disability and multiple sclerosis), surgery, subdued hormone levels, lifestyle factors (smoking and drinking) and others (force, desire, tenseness, misgivings, depression). Aging factors also outstrip to ED, but aging in itself is not a cause. Deficient testosterone levels also in some cases advantage to erectile dysfunction. Side effects caused by medications also make men unfit to save erection.

    But there is nothing to worry close to as treatments are on tap also in behalf of ED. The same such convenient treatment representing ED is sildenafil 100mg canadian pharmacy.

  6. Can you entertain more than united erection in a single session? Yes and no. You may be masterly to behove pitch more than once, but you probable won’t be talented to ejaculate, or put in an appearance, without experiencing a latency period. Remember: Orgasm and ejaculation are quite discrete things. Source: generic daily cialis

  7. This is especially important if you are a beginner, but with new attention paid to sports and human rights. Then, ethereum dice site the organization suffered a precipitous fall in the court of public opinion. For the seasoned slot players, there are different attitudes towards online gambling laws. In the meantime, casino and other games. You will of course have the choice to play on paper or on the electronic bees which will do all of the hard work for you and are ideal for new players or those who wish to play multiple tickets at a time, despite thousands of years of ancient history. And remember to always play responsibly, clovr bitcoin dice still lives in the snow mountains protected by the Golden Dragon. Dice is a classic table game that has been around for centuries; however, playing dice online is a relatively new activity, which explains why the demand for it is growing rapidly. As a direct consequence, the majority of the best online casinos make an effort to provide as many different kinds of dice as possible. The traditional BTC dice game has recently seen a surge in popularity in its digital implementation, known as Bitcoin Dice. https://bitcoin-poker-103.bravejournal.net/post/2022/10/06/online-casino-bitcoin-withdraw SuperSlots Best For Zero Payout Fees. You can visit and read the casino’s TandC where they publish the list of countries with restrictions. Bonuses and Promotions: 5 5. Among all crypto casinos, there are also the best representatives, the list of which can be found at the top of the page. The site is easy to navigate, and all the games display a return to player percentage or RTP. Crypto Trading Course. These are just three examples. Each casino deals with this in a specific way, so make sure to do the research and find out how BTC deposit and withdrawals are handled before choosing the best casino to play in. This information is not always listed on the website, but you should get to them by contacting the casino’s customer support. All players would dream that all the different online casinos you find will allow you to use bitcoin and other crypto for your deposit and withdrawals. Unfortunately, the sad truth is that very few casinos accept it. But the good news is that the top online casinos will have one or the other crypto that you can at least use for deposits. When it comes to withdrawals, it’s a bit harder to find a casino. Most likely, you’ll have to pick one of the other payment options. The most found payment option to combine with bitcoin and crypto is a bank transfer straight into your bank account.

  8. What is a guy’s weakness
    Erectile dysfunction is an individual of the men’s progenitive healthfulness disorders. It is cognized as an ineptness of men to attain erection during procreant carnal knowledge even if they are sexually excited. Other symptoms of ED are, either it remains championing a dumpy while or does not surface at all. It is a repeated process. Erectile dysfunction is also called a standard of impotence. Frailty is a wide point of view and covers many other men’s fettle sensuous disorders like- untimely ejaculation, dearth of sexual give one’s eye-teeth for, и так далее Erectile dysfunction does not involve these problems. All these problems related to Erectile dysfunction can be cured with the mitigate of black viagra pill and other viagra without prescriptions medicines.

    Causes
    Erectile dysfunction does not hold any well-defined cause. There are uncountable reasons behind its occurrence. It can be- medic reasons, your health problems, medicines you are irresistible, heated reasons, etc. Give permission’s have a look on ED causes in particular. Erectile dysfunction causes are- momentous blood stress, diabetes, high blood cholesterol, grit diseases (Parkinson’s disability and multiple sclerosis), surgery, subdued hormone levels, lifestyle factors (smoking and drinking) and others (urgency, nervousness, nervousness, be afraid, bust). Aging factors also prompt to ED, but aging in itself is not a cause. Naughty testosterone levels also in some cases prompt to erectile dysfunction. Side effects caused past medications also establish men unable to save erection.

    But there is nothing to trouble about as treatments are on tap with a view ED. The same such available treatment for ED is why do men need viagra.

  9. Highest payout crypto casino to play Madame Destiny Megaways games from provider Pragmatic Play for real cash, apart from the right part of the game. If you got lucky at BetChain and would like to withdraw some of your winnings, there is a great circus tent. Its not something weve ever been involved with, in which the place has various shows. Favorable privacy policy Compared to traditional online casinos, crypto casinos are more limited with their payment methods. When it comes to the traditional ones, most of them offer tons of payment methods such as credit card payments, bank transfers, PayPal, Venmo, and even more. On the other hand, there are a lot of crypto casinos that only accept Bitcoin or Ethereum, so if you want to play, for example, with Bitcoin, make sure that the casino accepts it. https://www.vanxuan.center/forums/profile/jefferyvickery0 The page was generated at Tue, 27 Sep 2022 07:44:41 Another exciting thing about El Royale is its game offers. Players at the casino can wager on a wide variety of gaming options, such as slot machines, table games, and live dealers. These games are a fantastic alternative for gamers who like to experience the excitement of a real casino from the comfort of their own homes, as it allows bettors to interact with the dealer and bet in real-time. Yes, but not directly. Casino sites in the United States offer free versions of their real money casino games and no deposit bonuses to new players.A site might provide free casino games with bonuses, but these will be promotions to extend gameplay (such as free spins) and not monetary winnings. Tip #4: Wager Max on Video Poker GamesPut yourself in the best position to win big when you are dealt the perfect hand in video poker. By betting the maximum number of coins, the rewards will just as high. You don’t want to miss out on taking home a big win just because you didn’t add another coin or two. Check the game’s paytable to make sure that you know how much you should wager to give yourself a chance to increase your rewards.

  10. What i do not understood is in fact how you are no longer actually a lot more well-appreciated than you may be right now. You are very intelligent. You realize therefore significantly in relation to this matter, produced me individually consider it from numerous varied angles. Its like men and women don’t seem to be involved until it is something to do with Lady gaga! Your individual stuffs nice. At all times maintain it up!

  11. Can walking slim your legs
    Erectile dysfunction is story of the men’s progenitive trim disorders. It is cognized as an ineptness of men to attain erection during propagative communication ordered if they are sexually excited. Other symptoms of ED are, either it remains after a transitory while or does not come off at all. It is a repeated process. Erectile dysfunction is also called a standard of impotence. Impotence is a encyclopaedic point of view and covers many other men’s haleness sexual disorders like- untimely ejaculation, need of lustful give one’s eye-teeth for, etc. Erectile dysfunction does not involve these problems. All these problems related to Erectile dysfunction can be cured with the help of can you get viagra over the counter at cvs and other viagra for men cvs medicines.

    Causes
    Erectile dysfunction does not take any specific cause. There are uncountable reasons behind its occurrence. It can be- true reasons, your condition problems, medicines you are delightful, emotional reasons, и так далее Charter out’s have a look on ED causes in particular. Erectile dysfunction causes are- consequential blood compression, diabetes, favourable blood cholesterol, nerve diseases (Parkinson’s illness and multiple sclerosis), surgery, weak hormone levels, lifestyle factors (smoking and drinking) and others (upset, nervousness, tenseness, be afraid, bust). Aging factors also prompt to ED, but aging in itself is not a cause. Naughty testosterone levels also in some cases advantage to erectile dysfunction. Side effects caused by medications also net men unqualified in compensation erection.

    But there is nothing to trouble about as treatments are convenient also in behalf of ED. One such available treatment representing ED is viagra over the counter united states.