Last active
August 29, 2015 13:58
-
-
Save kasei-san/10003192 to your computer and use it in GitHub Desktop.
スレッド操作いろいろ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <pthread.h> | |
#include <iostream> | |
class LedMatrix { | |
private: | |
pthread_t thread; // スレッドハンドラ | |
pthread_mutex_t mutex; // ミューテックス(排他処理で優先権を決めるやつ) | |
int data; | |
public: | |
LedMatrix(){ | |
data = 0; | |
} | |
// data に値を挿入 | |
// * execute が優先権を保持している間は待機する | |
// | |
void setData(int i){ | |
std::cout << "wait mutex" << std::endl; | |
pthread_mutex_lock(&(this->mutex)); // 優先権を保持するまで待機 | |
data = i; | |
pthread_mutex_unlock(&(this->mutex)); // 優先権を破棄 | |
std::cout << "set Data finished!" << std::endl; | |
} | |
int getData(){ return data; } | |
// ランチャ | |
// | |
static void* executeLauncher(void* args){ | |
std::cout << "executeLauncher" << std::endl; | |
// 引数に渡されたインスタンスを無理やりキャストして、インスタンスメソッドを実行 | |
reinterpret_cast<LedMatrix*>(args)->execute(); | |
return (void*)NULL; | |
} | |
// スレッド開始 | |
void threadStart(){ | |
if ((this->thread) == NULL){ | |
std::cout << "threadStart" << std::endl; | |
pthread_mutex_init(&(this->mutex), NULL); // ミューテックスの初期化 | |
pthread_create( // スレッドの生成 | |
&(this->thread), | |
NULL | |
&LedMatrix::executeLauncher, // スレッドにできるのは、static なメソッドや関数のみ | |
this | |
); | |
} | |
} | |
// スレッドで実行したいインスタンスメソッド | |
// | |
void execute(){ | |
while(1){ | |
pthread_testcancel(); // キャンセル要求が来ていたらここで終了 | |
pthread_mutex_lock(&(this->mutex)); // 優先権を保持するまで待機 | |
std::cout << "execute" << std::endl; | |
std::cout << "Data = " << (this->getData()) << std::endl; | |
sleep(10); // mutex_lock が判るように sleep を入れる | |
pthread_mutex_unlock(&(this->mutex)); // 優先権を破棄 | |
sleep(1); | |
} | |
} | |
// デストラクタ | |
// | |
~LedMatrix(){ | |
std::cout << "destructor start" << std::endl; | |
pthread_cancel(this->thread); // スレッドにキャンセル要求を投げる | |
pthread_join(this->thread, NULL); // スレッドが終了するまで待機 | |
std::cout << "destructor end" << std::endl; | |
} | |
}; | |
int main() | |
{ | |
LedMatrix* matrix = new LedMatrix(); | |
matrix->setData(10); | |
matrix->threadStart(); | |
sleep(1); | |
matrix->setData(20); | |
sleep(30); | |
delete matrix; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment