3
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?

More than 3 years have passed since last update.

Windows.hを使用したマルチスレッド(_beginthreadex()、CreateThread())

Last updated at Posted at 2021-08-15

マルチスレッド(並行処理)

複数スレッド(メインと生成したスレッド)があたかも同時に処理を実行しているように見える処理のこと。
並列処理は実際に同時に処理を実行している。
複数スレッドを交互に処理するため、画面出力などを行う際は、条件分岐やフラグなど使用して行う。
それでもタイミングがズレる場合は、同期制御(join)を行う。(windows.hにはjoinの関数がない?ため、クリティカルセクションやミューテックスなどを使用する。それか自分で同期制御の処理を作る。)

_beginthreadex()

int main(){
 int num1 = 30;

 HANDLE thread = _beginthreadex(NULL,0,func,NULL,0,NULL);

 while(num1 > 0){
  printf("num1 : %d\n",num1);
  num1--;
 }

 return 0;
}

static unsigned _stdcall func(){
 int num2 = 5;

 while(num2 > 0){
  printf("num2 : %d\n",num2);
  num2--;
 }

 _endthreadex(0);
}

_beginthreadex()は、実行後にスレッドが生成され、同時に実行する。

CreateThread()、ResumeThread()(SuspendThread())

int main(){
 int num1 = 30;

 HANDLE thread = CreateThread(NULL,0,func,NULL,0,NULL);
 ResumeThread(thread);

 while(num1 > 0){
  printf("num1 : %d\n",num1);
  num1--;
 }

 return 0;
}

static int func(){
 int num2 = 5;

 while(num2 > 0){
  printf("num2 : %d\n",num2);
  num2--;
 }

 return 0;
}

CreateThread()でスレッドを生成する。ResumeThread()でサスペンドカウンタをデクリメントし0にすることで、スレッドを実行する。サスペンドカウンタはスレッドオブジェクトの待機と実行を制御するカウンタで、0の場合は実行し、1の場合は待機をする。SuspendThread()をインクリメントし0以外にすることで、スレッドは待機をするらしいが、実際に使わなかったのでどういう挙動をしてどういうときに使用するのかは謎。スレッドの終わりにスレッド終了の関数を使わなくても、returnすれば終了する。

_beginthreadex()との違いは、生成と実行が分かれているため扱いが少々面倒くさい。CreateThread()でハンドルに渡し、ResumeThread()で実行し、スレッドが終了した後に再びResumeThread()で実行するためにはもう一度CreateThread()で生成しなければならない(一回実行したら死ぬ)。

3
1
0

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
3
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?