0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

atomicで別スレッドと同期をとる

Posted at
#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;
}

実行結果

image.png


失敗例:

#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;
}

実行結果

image.png

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?