Segmentation fault in std::thread::id's std::operator==

被刻印的时光 ゝ 提交于 2019-12-04 04:58:40
Ali

Statically linking libpthread into your applications is a really bad idea.

Nevertheless, here is how to do it.

I first fixed the compile errors (I suspect that you aren't showing us the code that you are actually compiling, or boost pollutes the namespace that much), then removed the irrelevant boost stuff, that only adds noise to the question. Here is the code:

#include <atomic>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>

int main(int, char*[])
{
    std::atomic<bool> exiting(false);

    std::vector<std::thread> threads;
    for ( int i = 0; i < 8; ++i ) {
        threads.push_back(std::thread([&exiting](){
            while (!exiting)
                std::cout << "thread " << std::this_thread::get_id() << " trace\n";
        }));
    }

    std::this_thread::sleep_for(std::chrono::milliseconds(1));

    exiting = true;

    for(auto& t : threads){
        t.join();
    };

    return 0;
}

It runs fine if I dynamically link but crashes when statically linked:

terminate called after throwing an instance of 'std::system_error'
  what():  Operation not permitted
Aborted (core dumped)

According to this e-mail the libstdc++ has to be configured appropriately if you use threads and statically link. Here are the magic flags to make it work with static linking:

g++ -std=c++11 -pedantic -pthread threads.cpp -static -Wl,--whole-archive -lpthread -Wl,--no-whole-archive

As I said before, statically linking libpthread into your application is asking for trouble.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!