マルチスレッドプログラム
#include <stdio.h>
#include <pthread.h>
main()
{
//スレッドの宣言
pthread_t thread;
//スレッドの生成
pthread_create(&thread,NULL,func,NULL);
//メインスレッドの処理
//threadの終了を待つ
pthread_join(thread,NULL);
}
void *func(void *arg)
{
//新しく作成した子スレッドの処理
//スレッド終了
pthread_exit(NULL);
}
★同期と排他処理
mutex(MUTual EXclusion:排他制御)
・共有データの同時更新からの保護
・2つの状態
アンロック状態(どのスレッドにも保有されていない)
ロック状態(1つのスレッドに保有されている)
・2つの異なるスレッドが同時にひとつのmutexを保有することはない
・他のスレッドによってロックされたmutexをロックしようとするスレッドは、保有側のスレッドが先にそのmutexをアンロックするまで実行を停止
★mutex
pthread_mutex_init()など
・書式
pthread_mutex_t mutex;
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
pthread_mutex_init:mutexが指すmutexオブジェクトを、mutexattrで指定されたmutex属性オブジェクトに従って初期化、mutexattrがNULLならば、デフォルトの属性が使われる
pthread_mutex_lock:与えられたmutexをロックする。他のスレッドによって既にロックされていたのならば、mutexがアンロックされるまで呼び出しスレッドの実行を停止させる
pthread_mutex_unlock:与えられたmutexをアンロックする
★排他制御プログラム例
#include <stdio.h>
#include <pthread.h>
//mutex生成
pthread_mutex_t mutex;
main()
{
pthread_t thread1, thread2;
//mutexの初期化
pthread_mutex_init(&mutex,NULL);
pthread_create(&thread1,NULL,func,NULL);
pthread_create(&thread2,NULL,func,NULL);
//メインスレッドの処理
pthread_join(thread,NULL);
}
void *func(void *arg)
{
//新しく作成した子スレッドの処理
//mutexのロック
pthread_mutex_lock(&mutex);
//ここに排他処理を記述
//mutexのアンロック
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
★まとめ
・マルチスレッドを使いたい例
-Webブラウザダウンロードと表示を並行して処理
-サーバが複数のクライアントを並行して処理
・マルチプロセスにはfork()を使う
・Win32のスレッド生成は_beginthreadex()かCreateThread()、mutex生成はCreateMutex()で行う
・参考URL
マルチスレッドプログラミング
http://www.ops.dti.ne.jp/~allergy/thread/thread.html
Pthreadリファレンス
http://www.saiin.net/~silphire/pthread/
JMプロジェクト
http://www.linux.or.jp/JM/
★(参考情報)Javaでスレッドを作成する場合
(パターン1:Runnableインタフェースを実装)
class ChildRun implements Runnable{
public void run(){
//子スレッドの処理
}
}
class ThreadTest{
public static void main(String[] args){
//スレッドの実行部を生成
ChildRun run = new ChildRun();
//スレッド生成
Thread thread = new Thread(run);
//スレッドの開始
thread.start();
//メインメソッドの処理
}
}
(パターン2:Threadクラスを継承)
class ChildThread extends Thread{
public void run(){
//子スレッドの処理
}
}
class ThreadTest{
public static void main(String[] args){
//スレッド生成
ChildThread thread = new ChildThread();
//スレッドの開始
thread.start();
//メインスレッドの処理
}
}
|