Mutex

概要

Mutexを使う

Glib::Muntexによって排他処理を行えるが、「Glib::thread_init()を呼ぶ前にGlib::Muntexを作ると例外が出る」。 従ってメンバ変数やグローバル変数でMuntexを作りたいときは代わりにGlib::StaticMutexを使う。

なおロックする際はGlib::Mutex::Lockを使うとアンロックし忘れを予防できるので便利である。

ソース

thread2.cpp

#include <gtkmm.h>
#include <iostream>

// gettid
#include <sys/types.h>
#include <linux/unistd.h>
_syscall0(pid_t,gettid)

// Glib::thread_init() する前は Glib::Mutex を作れないので
// 代わりに Glib::StaticMutex を作る
Glib::StaticMutex MyMutex = GLIBMM_STATIC_MUTEX_INIT;

void slot_thread()
{
    Glib::Mutex::Lock lock( MyMutex );

    for( int i = 0; i < 4 ; ++i ){
        std::cout << "thread tid = " << gettid() % 10 << std::endl;
        sleep( 1 );
    }
    std::cout << "thread stop(" << gettid() %10 << ")" << std::endl;
}

int main()
{
    // スレッドシステムの初期化
    Glib::thread_init();

    std::cout << "main tid = " << gettid() << std::endl;

    Glib::Thread* thread = Glib::Thread::create( sigc::ptr_fun( &slot_thread ), true );
    Glib::Thread* thread2 = Glib::Thread::create( sigc::ptr_fun( &slot_thread ), true );
    Glib::Thread* thread3 = Glib::Thread::create( sigc::ptr_fun( &slot_thread ), true );

    thread->join();
    thread2->join();
    thread3->join();

    std::cout << "main stop(" << gettid() << ")" << std::endl;
}

コンパイル

必要なコンパイルオプションは pkg-config を使って取得する。今回はスレッドを 使用しているので pkg-config --libs gthread-2.0 の指定も必要である。

g++ thread2.cpp -o thread2 `pkg-config gtkmm-2.4 --cflags --libs` `pkg-config --libs gthread-2.0`

結果

mutexを有効にした場合は
main tid = 16874
thread tid = 5
thread tid = 5
thread tid = 5
thread tid = 5
thread stop(5)
thread tid = 6
thread tid = 6
thread tid = 6
thread tid = 6
thread stop(6)
thread tid = 7
thread tid = 7
thread tid = 7
thread tid = 7
thread stop(7)
main stop(16874)
一方、Glib::Mutex::Lock lock( MyMutex );の行を消してmutexを無効にした場合は
main tid = 16789
thread tid = 0
thread tid = 1
thread tid = 2
thread tid = 0
thread tid = 1
thread tid = 2
thread tid = 0
thread tid = 1
thread tid = 2
thread tid = 0
thread tid = 1
thread tid = 2
thread stop(0)
thread stop(1)
thread stop(2)
main stop(16789)