#include <unistd.h>
#include <atomic>
#include <iostream>
#include <thread>
// 引数でatomicの変数を参照型で受け取る
void thread_func(std::atomic<bool>& alive_flg)
{
for (int i = 0; i < 1000; ++i) {
usleep(1000);
}
alive_flg = false;
}
int main()
{
std::atomic<bool> alive_flg{0};
std::uint32_t loop_counter = 0;
while(true)
{
static bool initailized = false;
static std::thread thread_ins;
if(initailized == false)
{
alive_flg = true;
// スレッド作成:参照型の引数はstd::ref(変数)で渡す
std::thread t1{thread_func, std::ref(alive_flg)};
thread_ins.swap(t1);
initailized = true;
}
else if(alive_flg == false)
{
thread_ins.join();
break;
}
loop_counter++;
}
std::cout << "loop counter : " << loop_counter << std::endl;
return 0;
}
実行結果
失敗例:
#include <unistd.h>
#include <atomic>
#include <iostream>
#include <thread>
void thread_func(std::atomic<bool>& alive_flg)
{
for (int i = 0; i < 1000; ++i) {
usleep(1000);
}
alive_flg = false;
}
int main()
{
std::atomic<bool> alive_flg{0};
std::uint32_t loop_counter = 0;
while(true)
{
static bool initailized = false;
// インスタンスを自動変数で定義すると
// 確保したスレッドコンテキストが破棄され例外が発生
std::thread thread_ins;
if(initailized == false)
{
alive_flg = true;
std::thread t1{thread_func, std::ref(alive_flg)};
thread_ins.swap(t1);
initailized = true;
}
else if(alive_flg == false)
{
thread_ins.join();
break;
}
loop_counter++;
}
std::cout << "loop counter : " << loop_counter << std::endl;
return 0;
}

