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
?
Asked
Active
Viewed 1.4k times
10

Adrian Mole
- 49,934
- 160
- 51
- 83

WhatIf
- 653
- 2
- 8
- 18
1 Answers
16
There are multiple adavantages. Listing those, not neccessarily in the order of importance.
- It is cross-platform. For instance, pthreads library by default is not available on Windows. Using thread guarantees that available implementation will be used.
- 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.
- 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.
- 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!

SergeyA
- 61,605
- 5
- 78
- 137
-
@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...) – Chris Aug 23 '16 at 23:05
-
3@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 :) – SergeyA Aug 24 '16 at 14:27