segmentation fault using static libraries with std::jthread (g++-10)
Asked Answered
L

1

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();
}
Ligure answered 28/6, 2020 at 22:30 Comment(6)
Try replacing -lpthread with -pthread. That's what you should always use anyway. Edit: That doesn't seem to help: godbolt.org/z/y_Fg2PDiscretion
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.Phew
It is apparently related to #35116827 !Phew
As an aside, calling own programs test is confusing.Polypody
@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.Polypody
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.Watery
L
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.

Ligure answered 11/11, 2020 at 18:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.