Advantage of std::thread over pthread in C++

13,090

There are multiple adavantages. Listing those, not neccessarily in the order of importance.

  1. It is cross-platform. For instance, pthreads library by default is not available on Windows. Using thread guarantees that available implementation will be used.
  2. C++ threads enforce proper behaviour. For instance, an attempt to destruct a handle of not-joined, not-detached thread causes a program to abort. This is a very good thing, as it makes people aware of what they are doing.
  3. C++ threads are fully incorporated into C++ as a language. No longer you have to resort to allocating your arguments in some sort of struct and passing address of this struct as a void* to your pthread routine. By using variadic templates, C++ thread library allows you to provide any number of arguments you want to your thread start routine, and does type check for you.
  4. C++ threads have a nice set of surrounding classes, such as promise. Now you can actually throw exceptions from your threads without causing the whole program to crash!
Share:
13,090
WhatIf
Author by

WhatIf

Updated on July 19, 2022

Comments

  • WhatIf
    WhatIf almost 2 years

    I have seen code that uses pthread to write multi-threaded programs in C++ and other codes that use the std::thread library. What is the advantage of using the thread library instead of pthread?

  • Chris
    Chris over 7 years
    @SergeyA as a newbie C++ user...should I fully embrace this, or should I go through the pain of learning this pointer(pointer){function(&pointer)} system of pthreads? Would it be worth my time? Or is it just a waste of time? (In a class, limited learning time...)
  • SergeyA
    SergeyA over 7 years
    @bordeo, I am not in favor of giving such broad suggestions. I believe, pointer-to-functions style is still relevant in C++, but obviously it is getting more and more out of favor and deprecated. I'd say, learn about it, understand how it works and never use it :)