3

In c++ if I write a program using pthreads (using cmake as my build system and assuming I'm on a unix based system like OS X or Redhat), what is the difference between using pthread.h:

#include <iostream>
#include <pthread.h>
using namespace std;

void* print_message(void*) {
    cout << "Threading\n";
}

int main() {
    pthread_t t1;
    pthread_create(&t1, NULL, &print_message, NULL);
    return 0;
}

and using std::thread with a pthread compile flag:

#include <iostream>
#include <thread>
using namespace std;

void print_message() {
    cout << "Threading\n";
}

int main() {
    std::thread t1(&print_message);
    t1.join();
    return 0;
}

with the flags:

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app Threads::Threads)

(examples taken from here and here

Community
  • 1
  • 1
thed0ctor
  • 1,350
  • 4
  • 17
  • 34

1 Answers1

0

The difference is between a built-in language feature and a library. They might have the same purpose.

std::thread is a feature of C++11. If you have a C++11 compliant compiler, it will work. Some compilers require to set a flag to enable the right C++ mode, but this is not a general rule.

For threading library you need to find out the flags and includes that must be passed for compilation and linking. There might be version numbers you have to account for. You can do that with CMake, but it requires work, testing and it complicates your CMake files a little bit.

usr1234567
  • 21,601
  • 16
  • 108
  • 128
  • 1
    Note that when using `std::thread` you _still_ need the pthread flag on some platforms (like gcc on Linux). That's why the `find_package(Threads)` call is still relevant, even when you are targetting only C++11-compliant compilers. – ComicSansMS Nov 11 '15 at 14:11
  • I would say it's not a language feature, it's in the standard library – bolov Nov 12 '15 at 07:22
  • @bolov: I would say the standard library is part of the C++ language. I would say C++ language is everything and can be sub-categorized in compiler features and library features. For a user this distinction is not relevant. – usr1234567 Nov 12 '15 at 07:38