9

I'm developing a library that works with std::jthread (new in C++20) using g++ 10.0.1. The library works fine if I compile it using share libraries, but If I compile it with static libraries I got a segmentation fault at the end of the program (thread destructor). I have narrowed down my test case to a simple thread creation and join:

#include <iostream>
#include <thread>

int main(int argc, const char** argv) {
  auto t = std::jthread([]() { std::cout << "OK\n"; });
  t.join();
  return 0;
}

To compile I use:

g++-10 -o test --static -std=c++20 test.cc -lpthread 

And running it:

% ./test
zsh: segmentation fault (core dumped)  ./test

There any one has an idea what this problem could be?

Update:

Following @JérômeRichard suggested reference, I was able to compile and run my little test program without problem

g++-10 -o test --static -std=c++20 test.cc -lrt -pthread  -Wl,--whole-archive -lpthread -Wl,--no-whole-archive

However, changing the code to use request_stop instead of join the program is segmenting fault again (https://godbolt.org/z/obGN8Y).

#include <iostream>
#include <thread>

int main() {
    auto t = std::jthread([]{ std::cout << "OK" << std::endl; });
    t.request_stop();
}
abuss
  • 91
  • 3
  • Try replacing `-lpthread` with `-pthread`. That's what you should always use anyway. Edit: That doesn't seem to help: https://godbolt.org/z/y_Fg2P – Ted Lyngmo Jun 28 '20 at 22:41
  • 2
    It seems the issue is related to the `--static`: without, no segmentation faults are reported. Note that a similar problem also appear with the regular `std::thread` on older version of GCC (eg. GCC 9) and without the `-std=c++20`. – Jérôme Richard Jun 28 '20 at 22:44
  • 1
    It is apparently related to https://stackoverflow.com/questions/35116327/when-g-static-link-pthread-cause-segmentation-fault-why ! – Jérôme Richard Jun 28 '20 at 22:55
  • As an aside, calling own programs `test` is confusing. – Peter - Reinstate Monica Jun 28 '20 at 23:06
  • @JérômeRichard I should think that the answer there will solve this problem as well. Curious whether it will work for the OP here. Btw, the most upvoted answer there is an interesting lecture on the inner workings of glibc and the linker, static vs. dynamic linking and weak/strong symbols. – Peter - Reinstate Monica Jun 28 '20 at 23:13
  • `request_stop` is inappropriate to call unless you are cooperatively cancelling the thread. `join()` is proper here. That said, it appears to work with the latest version of gcc. – AndyG Oct 08 '20 at 12:34

1 Answers1

0

The problem was reported to libstdc++ (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95989) and a patch has been generated to solve the problem.

abuss
  • 91
  • 3