YouTube Icon

Interview Questions.

Top 100+ C++ Multithreading Developer Interview Questions And Answers - May 28, 2020

fluid

Top 100+ C++ Multithreading Developer Interview Questions And Answers

Question 1. What Header File Should You Include For Using C++11 Multithreading Capabilities?

Answer :

Use the <thread> header file

#consist of <thread>

Note: The thread capability is defined inside the "std" namespace.

Question 2. What Are The Different Ways Of Creating A Thread In C++eleven?

Answer :

There are basically four methods of making a thread:

Create a thread with a function pointer
Create a thread with a characteristic object
Create a thread with a lambda
Create a thread with a member feature
HTML Interview Questions
Question three. How Can A C++eleven Thread Be Created With A Function Pointer?

Answer :

Just bypass in the deal with of a feature to the thread constructor. The thread will start executing the feature right away.

#include "stdafx.H"

#include <thread>

#encompass <iostream>

the usage of namespace std;

void FireMissile()

  cout << "Firing sidewinder missile " << endl;

int essential()

  //Creating a thread with a function pointer

  thread t1(FireMissile);

  t1.Be part of();

  go back zero;

Question four. How Can A C++eleven Thread Be Created With A Function Object?

Answer :

Create a characteristic object "Missile" and skip it to the thread constructor.

#encompass "stdafx.H"

#include <thread>

#encompass <iostream>

the use of namespace std;

//Create the function object

magnificence Missile

public:

  void operator() () const

  

    cout << "Firing Tomahawk missile" << endl;

  

;

int primary()

  //Creating a thread with an characteristic item

  Missile tomahawk;

  thread t1(tomahawk);

  t1.Be a part of();

  return zero;

HTML Tutorial
Question 5. How Can A C++eleven Thread Be Created With A Lambda?

Answer :

#consist of "stdafx.H"

#include <thread>

#include <iostream>

using namespace std;

int main()

  thread t1([] 

    cout << "Launching Scud missile" << endl;

  );

  t1.Be a part of();

  go back zero;

HTML five Interview Questions
Question 6. Can A Lambda Closure Be Used To Create A C++eleven Thread?

Answer :

Yes ! A lambda closure is not anything however a variable storing a lambda expression. You can keep a lambda in a closure in case you intend to reuse the lambda expression at a couple of vicinity to your code.

#encompass "stdafx.H"

#encompass <thread>

#consist of <iostream>

using namespace std;

int predominant()

  // Define a lambda closure

  vehicle LaunchMissileFunc = []() -> void  cout << "Launching Cruiser Missile" << endl; ;

  thread t1(LaunchMissileFunc);

  t1.Be part of();

  return 0;

Question 7. How Can A C++11 Thread Be Created With A Member Function?

Answer :

#encompass "stdafx.H"

#include <thread>

#encompass <iostream>

the usage of namespace std;

class Torpedo

public:

  void LaunchTorpedo()

  

    cout << " Launching Torpedo" << endl;

  

;

int most important()

  //Execute the LaunchTorpedo() method for a selected Torpedo object on a seperate thread

  Torpedo torpedo;

  thread t1(&Torpedo::LaunchTorpedo, &torpedo);

  t1.Be a part of();

  go back 0;

Note that here you're executing the LaunchTorpedo() approach for a selected Torpedo item on a seperate thread. If different threads are gaining access to the identical "torpedo" item, you may need to defend the shared assets of that item with a mutex.

HTML five Tutorial C++ Interview Questions
Question 8. What Does Joining C++11 Threads Mean? Alternatively What Does The Std::thread::join() Do?

Answer :

A call to std::thread::be a part of() blocks until the thread on which join is called, has finished executing. In each of the examples above, the join() name ensures that the principle approach waits for the execution of the spawned threads to finish earlier than it could go out the utility.

On the alternative hand, if we do not name be part of() after growing a thread in the above case, the main characteristic will no longer watch for the spawned thread to complete before it tears down the application. If the software tears down earlier than the spawned thread finishes, it'll terminate the spawned thread as properly, even though it has no longer completed executing. This can depart statistics in a completely inconsistent country and should be averted at all price.

Question 9. Can You Name A Situation Where Joining Threads Should Be Avoided?

Answer :

A name to sign up for() blocks the caller thread. This is without a doubt bad in conditions in which the caller thread is a chief UI thread – due to the fact if the UI thread blocks, the utility will prevent responding to person inputs in order to make it appear hanged.

Another place wherein calling be part of() isn't always recommended is inside a main recreation loop. Calling be part of() can block replace and rendering of the game scene and severly effect the person enjoy (it is going to be like watching a You tube video on a dial up internet connection !).

C Interview Questions
Question 10. Can You Create A C++eleven Thread With A Function Pointer That Takes A Bunch Of Arguments?

Answer :

Yes ! You can simply skip the characteristic arguments to the thread constructor. The thread constructor is a variadic template, which means it could receive any range of arguments. Here's an instance:

#consist of "stdafx.H"

#include <string>

#encompass <thread>

#consist of <iostream>

using namespace std;

void FireTorpedo(int numCities, string torpedoType)

  cout << "Firing torpedo " << torpedoType << " at" << numCities << " towns." << endl;

int main()

  thread t1(FireTorpedo, 3, "HungryShark");

  t1.Join();

  return 0;

C++ Tutorial
Question 11. Can You Create A C++11 Thread With A Lambda Closure That Takes A Bunch Of Arguments?

Answer :

Yes – just like the previous case, you can pass the arguments needed by the lambda closure to the thread constructor.

Auto LaunchTorpedoFunc = [](int numCities, string torpedoType) -> void  cout << "Firing torpedo " << torpedoType << " at" << numCities << " towns." << endl; ;

thread t1(LaunchTorpedoFunc, 7, "Barracuda");

t1.Join();

SQL Server 2008 Interview Questions
Question 12. Are The Arguments Passed To A C++eleven Thread's Constructor Pass By Vale Or Pass By Reference?

Answer :

Thread function arguments are constantly bypass by using value, i.E., they may be usually copied into the inner garage for threads. Any adjustments made with the aid of the thread to the arguments exceeded does now not affect the unique arguments. For instance, we need the "targetCity" to be changed with the aid of the thread however it in no way takes place:

#encompass "stdafx.H"

#include <string>

#consist of <thread>

#consist of <iostream>

#consist of <functional>

the usage of namespace std;

void ChangeCurrentMissileTarget(string& targetCity)

  targetCity = "Metropolis";

  cout << " Changing The Target City To " << targetCity << endl;

int foremost()

  string targetCity = "Star City";

  thread t1(ChangeCurrentMissileTarget, targetCity);

  t1.Join();

  cout << "Current Target City is " << targetCity << endl;

  return 0;

OUTPUT:

Changing The Target City To Metropolis

Current Target City is Star City

Note that the "targetCity" variable is not modified.

HTML Interview Questions
Question 13. How Can We Pass C++eleven Thread Arguments By Reference?

Answer :

We want to use std::ref() from the <functional> header. Consider the following code snippet and associated output.

#consist of "stdafx.H"

#consist of <string>

#consist of <thread>

#encompass <iostream>

#encompass <functional>

using namespace std;

void ChangeCurrentMissileTarget(string& targetCity)

  targetCity = "Metropolis";

  cout << " Changing The Target City To " << targetCity << endl;

int foremost()

  string targetCity = "Star City";

  thread t1(ChangeCurrentMissileTarget, std::ref(targetCity));

  t1.Be a part of();

  cout << "Current Target City is " << targetCity << endl;

  go back zero;

OUTPUT:

Changing The Target City To Metropolis

Current Target City is Metropolis

Notice that the modifications to "targetCity" made by way of the thread was preserved as soon as the thread exited.

C Tutorial
Question 14. Does A C++11 Thread Act On A Specific Instance Of A Function Object?

Answer :

No – characteristic items are copied to the inner storage for the thread. If you need to execute the operation on a specific instance of the function item, you need to use std::ref() from <functional> header to skip your feature item by means of reference.

Question 15. How Can You Create Background Tasks With C++eleven Threads?

Answer :

You can make a std::thread run in the history by calling std::thread::detach() on it. Once detached, a thread continues to run within the history and can not be communicated with or waited upon to finish. When you detach a thread, the possession and manipulate passes over to the C++ Runtime Library, which ensures that the resources allocated to the thread are deallocated as soon as the thread exits.

Here's a contrived example. We have a Count() characteristic that prints numbers 1 to 1000 at the screen. If we create a thread to run the feature and detach the thread at once, we're going to not see any output – because the primary thread terminates earlier than the "Count" thread has had an opportunity to run. To see a number of the output, we will placed the main thread to sleep for 10 miliseconds which gives the "matter" thread to ship a number of the output to the display.

#consist of "stdafx.H"

#consist of

#consist of

#include

#encompass

using namespace std;

void Count()

  for (int i = 0; i < a hundred; i++)

  

    cout << "counter at: " << i << endl;

  

int primary()

  thread t1(Count);

std::this_thread::sleep_for(std::chrono::milliseconds(10));

  t1.Detach();

  go back zero;

Oracle Interview Questions
Question sixteen. Can The Ownership Of C++eleven Threads Be Transferred At Runtime?

Answer :

Yes. Std::thread object owns a resource, where the resource is a contemporary thread of execution. You can name std::move to move the ownership of the underlying aid from one std::thread object to any other. The query is – why might you need to do this? Here's a state of affairs:You need to write a feature that creates a thread but does no longer need to wait for it to complete. Instead it wants to pass the thread to another characteristic so one can look ahead to the thread to complete and execute a few action once the execution is performed.

#include "stdafx.H"

#encompass <string>

#include <thread>

#include <iostream>

#encompass <functional>

using namespace std;

void FireHTTPGet()

std::this_thread::sleep_for(std::chrono::milliseconds(5000));

  cout << "Finished Executing HTTP Get"<< endl;

void ProcessHTTPResult(thread t1)

  t1.Be part of();

  cout << "HTTP Get Thread Finished Executing - Processing Result Data!" << endl;

int fundamental()

  thread t11(FireHTTPGet);

  thread t12(ProcessHTTPResult, std::flow(t11));

  //Do bunch of different processing with out anticipating t11 to complete - instead now we have shouldered off the 

  // obligation of monitoring t11 thread to t12.

  //Finally anticipate t12 to finish

  t12.Join();

  return 0;

OUTPUT:

Finished Executing HTTP Get

HTTP Get Thread Finished Executing - Processing Result Data!

SQL Server 2008 Tutorial
Question 17. What Is C++11 Thread Local Storage (thread_local)?

Answer :

A thread_local item comes into existence when a thread begins and is destroyed when the thread ends. Each thread has its personal instance of a thread-Local item.

To completely recognize the results, allow's study an example- here we will claim a worldwide variable "globalvar" as thread_local. This'll deliver every thread it's very own reproduction of globalVar and any changes made to globalVar will simplest persist inside that unique thread.In the instance beneath, each of the 2 threads are enhancing globalVar – however they may be no longer seeing each different's alternate, neither is the principle thread.

#consist of "stdafx.H"

#encompass <string>

#consist of <thread>

#consist of <iostream>

#consist of <functional>

#consist of <mutex>

the use of namespace std;

thread_local int globalVar = 0;

mutex mu;

void PrettyPrint(int valueToPrint)

  lock_guard<mutex> lock(mu);

  cout << "Value of globalVar in thread " << this_thread::get_id() << " is " << globalVar << endl;

void thread_Local_Test_Func(int newVal)

  globalVar = newVal;

  PrettyPrint(globalVar);

int most important()

  globalVar = 1;

  thread t1(thread_Local_Test_Func, five);

  thread t2(thread_Local_Test_Func, 20);

  t1.Be part of();

  t2.Be a part of();

  cout << "Value of globalVar in MAIN thread is " << globalVar << endl;

    go back zero;

Here's the output of the program – you can see that the three threads (t1, t2 and MAIN) does no longer see every different's modifications to globalVar.

Value of globalVar in thread 17852 is five

Value of globalVar in thread 29792 is 20

Value of globalVar in MAIN thread is 1

Can you guess what the output might be if globalVar changed into now not declared thread_local ? Here it is :

Value of globalVar in thread 27200 is five

Value of globalVar in thread 31312 is 20

Value of globalVar in MAIN thread is 20

If the global cost changed into no longer thread local, the alternate made by means of every thread can be persisted outside the thread – here the MAIN thread is feeling the impact  of the alternate made through t2 and hence printing "20" rather than "1".

ASP.NET Interview Questions
Question 18. How Can You Retrieve Results From A Thread?

Answer :

As we're going to see in a next academic, the easiest and endorsed manner is to use "futures". However, you can still get the result of a few calculation from a thread via both:

Passing reference to a end result variable to the thread in which the thread stores the consequences

Store the end result interior a category memeber variable of a function item which may be retrieved once the thread has completed executing.

HTML five Interview Questions
Question 19. What Is "oversubscription"?

Answer :

Oversubscription is a state of affairs wherein greater threads are vying for runtime than the underlying hardware can support. One of the largest fee associated with a couple of threads is that of context-switches that takes place when the processor switches threads. Ideally, the you'll not need to create greater threads than the hardware can aid.

ASP.NET Tutorial
Question 20. How Can I Avoid "oversubscription" In C++eleven When Working With Multiple Threads?

Answer :

C++11 offers a way to get a touch at the number of threads that can be run in parallel from an utility – which maximum of the time coincides with the quantity of logical cores.

Unsigned int n = std::thread::hardware_concurrency();

On my machine with 12 logical cores, it returns 12. This means that I ought to now not try and fork extra than 12 threads in my utility. Note that this is VC++ – other C++ compiler implementations would possibly supply exclusive consequences

Linux Interview Questions
Question 21. How Can You Identify Different C++eleven Threads?

Answer :

C++eleven gives precise ids to forked threads which may be retrieved the usage of :

By calling the get_id() member feature for a selected thread

By calling std::this_thread::get_id() for the currently executing thread

An instance of each is given below:

#include "stdafx.H"

#encompass <string>

#consist of <thread>

#consist of <iostream>

#consist of <functional>

the usage of namespace std;

void Count()

  for (int i = 0; i < one hundred; i++)

  

    cout << "counter at: " << i << endl;

  

int main()

thread t22(Count);

  //Get the ID of the t22 thread

  std::thread::identity okay = t22.Get_id();

  cout << ok << endl;

  //Get the ID of the MAIN Thread

  std::thread::id j = std::this_thread::get_id();

  cout << j << endl;

  go back zero;

If I run this code, I can see the thread ids in "threads" and "locals" window. Also notice that the thread name is nearly vain.

However, the "Location" column can supply an illustration as to which thread is executing.




CFG