Thursday, 13 October 2016

multithreading : thumb rules.


  1. If two threads are sharing same resource, then parent thread who own the resource, will wait for child thread to complete its work before termination.
  2. Once you join or detach the thread, you will not be able to join or detach it again. In C++, once you detach the thread and try to join it back to parent thread, you may end up with undefined behavior,  as a C++ programmer, you know that, most of the time undefined behavior means crash. So once thread is detach/join it will be in detach/join state forever, we can not detach/join it back again.
  3. How to calculate how many threads to create for my application?
    • Ideally as many numbers of cores are there in your processor.
    • We shall not create many threads, which our hardware can not handle, as too much context switching between threads will slow down the system. 
    • Also it is not strictly limited to the number of cores, as it is a good ides to go little higher (in numbers) then the actual number of cores, but higher has limit, otherwise you will end up with a problem as mentioned above (second point).
    • Thankfully in C++ we have a library function which will give you a very close idea about your hardware, it tells how many threads your hardware can handle easily - std::thread::hardware_concurrency(), so this function will give you answer.

Thanks for reading this, please write questions or some more useful information related to this topic on comment section. To learn more about threading, see the full learning index here, or join multithreading learning page on FB or on G++.

No comments:

Post a Comment