I’ve read through other answers that signals are delivered to any arbitrary thread; however, with my own testing:
#include <iostream>
#include <thread>
#include <vector>
#include <chrono>
void foo(int i) {
while (true) {
std::cout << i << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main() {
std::vector<std::thread> t;
for (int i = 0 ; i < 5 ; i++) {
t.emplace_back([=] {
foo(i);
});
}
for (auto& v : t)
v.join();
}
I determined three things:
- if I do not
detach
orjoin
, I get an abort fromlibc++abi
- if I
detach
each thread as it’s spawned, I immediately exit and see no output - if I
join
, there is the expected behavior, but a signal kills all threads
Could someone please explain these behaviors? I’m concerned primarily with getting all threads to exit on receiving a signal (with as little code as possible) but the behaviors are curious to me.
My thoughts on each of these are:
- potentially undefined behavior
main
exiting kills all threads (this strikes me as strange)- this last one is very unexpected, since I thought a signal is delivered to random thread and only kills that one