使用std :: thread和make flag -pthread以及使用pthread.h库有什么区别?

时间:2015-11-10 22:56:12

标签: multithreading c++11 cmake

在c ++中,如果我使用pthreads编写程序(使用cmake作为我的构建系统并假设我使用的是基于unix的系统,如OS X或Redhat),使用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;
}

并使用带有pthread编译标志的std :: thread:

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

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

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

带有标志:

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

(取自herehere

的示例

1 个答案:

答案 0 :(得分:0)

区别在于内置语言功能和库。他们可能有相同的目的。

std :: thread是C ++ 11的一个特性。如果你有一个C ++ 11兼容的编译器,它将工作。有些编译器需要设置一个标志来启用正确的C ++模式,但这不是一般规则。

对于线程库,您需要找出必须传递以进行编译和链接的标志和包含。您可能需要考虑版本号。你可以用CMake做到这一点,但它需要工作,测试,它会使你的CMake文件变得复杂。