
質問内容
以下の処理内容部ですが、タイトル通りでstd::thread の利用で detachした複数の無限ループのスレッドをすべて終了させる方法が知りたい が知りたいです、現状は下記のように実装しているのですが本当はどうやって実装するのでしょうか?
知りたいこと
std::thread の利用でdetachした複数の無限ループのスレッドをすべて終了させる方法が知りたい
処理内容
以下の無限ループの処理のコードなのですが、websocketを用いた無限ループして処理を受け付ける処理ですそのコードのstatsu変数を用いて、メインスレッドから終了のキー入力を受け付けるとループ処理が抜けます、その後Close()関数ではすべてのスレッドの無限ループが抜けるまで無限ループを繰り返してその後すべて終われば無限ループを抜けて処理を抜けてmain関数の処理が終了してプログラムが終了するという処理です、
クロース処理関数
cpp
1 2void Mastodon::Instance::Close() 3{ 4 for(std::map<std::string,Status>::iterator itr = status.begin(); itr != status.end(); itr++) 5 { 6 itr->second.isLoop = false; 7 } 8 9 bool isCheck = false; 10 11 while(isCheck == false) 12 { 13 bool isRestart = false; 14 for(std::map<std::string,Status>::iterator itr = status.begin(); itr != status.end(); itr++) 15 { 16 if(itr->second.isEixt == false) 17 { 18 isRestart = true; 19 break; 20 } 21 } 22 23 if(isRestart == false) 24 { 25 std::cout<<"process exit"<<std::endl; 26 ws_client.close().wait(); 27 break; 28 } 29 30 } 31// ws_client.close().wait(); 32}
websocketによる無限ループスレッド
cpp
1 2void Mastodon::Instance::Stream(std::function<void(web::websockets::client::websocket_incoming_message)> func,web::http::uri_builder uri) 3{ 4 status[uri.to_string()] = Status{false,false}; 5 if(ws_client.connect(uri.to_uri()).wait() == pplx::task_status::completed) 6 { 7 status[uri.to_string()] = Status{true,false}; 8 while(status[uri.to_string()].isLoop == true) 9 { 10 ws_client.receive().then([func](web::websockets::client::websocket_incoming_message msg) 11 { 12 if(msg.message_type() == web::websockets::client::websocket_message_type::text_message) 13 { 14 func(msg); 15 } 16 else 17 { 18 if(msg.message_type() == web::websockets::client::websocket_message_type::ping) 19 { 20 std::cout << "Ping " << msg.extract_string().get() << std::endl; 21 } 22 else 23 { 24 std::cout << "other type" << std::endl; 25 } 26 } 27 28 }).wait(); 29 } 30 } 31 status[uri.to_string()] = Status{false,true}; 32} 33

質問文は意味がないので読んでませんが、pthreadがnativeな環境でstd::threadのjoinの動きを見てみました。
$ cat hoge.sh
cat >hoge.cpp <<EOF
#include <thread>
#include <chrono>
#include <iostream>
int main(int argc, char* argv[]) {
std::thread t([]{
for(auto i = 0; i < 3; ++i) {
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "thread running..." << std::endl;
}
});
if (argc > 1) {
auto native_id = t.native_handle();
t.detach();
std::cout << native_id << std::endl;
std::cout << (pthread_join(native_id, nullptr) == EINVAL ? "EINVAL" : "not EINVAL") << std::endl;
} else {
t.join();
}
return 0;
}
EOF
g++ -pthread -Wall -pedantic -g hoge.cpp -o hoge
echo "join end"
./hoge
echo "detach end"
./hoge 1
$ bash hoge.sh
join end
thread running...
thread running...
thread running...
detach end
140420052784896
EINVAL
$
detachされたスレッドはpthread_joinすら失敗するようですね。
