Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of std::thread over pthread in C++ [duplicate]

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?

like image 570
WhatIf Avatar asked Sep 14 '15 20:09

WhatIf


People also ask

Does std :: thread use pthreads?

The std::thread library is implemented on top of pthreads in an environment supporting pthreads (for example: libstdc++).

What is the advantage of OpenMP over pthreads?

On the other hand, OpenMP is much higher level, is more portable and doesn't limit you to using C. It's also much more easily scaled than pthreads. One specific example of this is OpenMP's work-sharing constructs, which let you divide work across multiple threads with relative ease.

What does std :: thread do?

std::thread Threads allow multiple functions to execute concurrently. std::thread objects may also be in the state that does not represent any thread (after default construction, move from, detach, or join), and a thread of execution may not be associated with any thread objects (after detach).

Does C++ thread use Pthread?

Thread functions in C/C++ In a Unix/Linux operating system, the C/C++ languages provide the POSIX thread(pthread) standard API(Application program Interface) for all thread related functions. It allows us to create multiple threads for concurrent process flow.


1 Answers

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!
like image 98
SergeyA Avatar answered Oct 14 '22 02:10

SergeyA