工業製造
産業用モノのインターネット | 工業材料 | 機器のメンテナンスと修理 | 産業プログラミング |
home  MfgRobots >> 工業製造 >  >> Industrial programming >> C言語

C++ マルチスレッド

マルチスレッドは、マルチタスクの特殊な形式であり、マルチタスクは、コンピューターで 2 つ以上のプログラムを同時に実行できるようにする機能です。一般に、マルチタスクにはプロセスベースとスレッドベースの 2 種類があります。

プロセスベースのマルチタスキングは、プログラムの同時実行を処理します。スレッドベースのマルチタスキングは、同じプログラムの断片の同時実行を処理します。

マルチスレッド プログラムには、同時に実行できる 2 つ以上の部分が含まれます。このようなプログラムの各部分はスレッドと呼ばれ、各スレッドは個別の実行パスを定義します。

C++ には、マルチスレッド アプリケーションの組み込みサポートは含まれていません。代わりに、この機能を提供するためにオペレーティング システムに完全に依存しています。

このチュートリアルでは、Linux OS で作業していて、POSIX を使用してマルチスレッド C++ プログラムを作成することを前提としています。 POSIX スレッドまたは Pthreads は、FreeBSD、NetBSD、GNU/Linux、Mac OS X、Solaris など、多くの Unix ライクな POSIX システムで利用できる API を提供します。

スレッドの作成

次のルーチンは、POSIX スレッドを作成するために使用されます −

#include <pthread.h>
pthread_create (thread, attr, start_routine, arg) 

ここで、pthread_create 新しいスレッドを作成し、実行可能にします。このルーチンは、コード内のどこからでも何度でも呼び出すことができます。パラメータの説明は次のとおりです-

Sr.No パラメータと説明
1

スレッド

サブルーチンによって返される新しいスレッドの不透明で一意の識別子。

2

属性

スレッド属性の設定に使用できる不透明な属性オブジェクト。スレッド属性オブジェクトを指定するか、デフォルト値として NULL を指定できます。

3

start_routine

作成後にスレッドが実行する C++ ルーチン。

4

引数

start_routine に渡すことができる単一の引数。これは、型 void のポインター キャストとして参照渡しする必要があります。引数を渡さない場合は、NULL を使用できます。

プロセスによって作成されるスレッドの最大数は、実装によって異なります。作成されたスレッドはピアであり、他のスレッドを作成する場合があります。スレッド間に暗黙の階層や依存関係はありません。

スレッドの終了

POSIXスレッドを終了するために使用する次のルーチンがあります-

#include <pthread.h>
pthread_exit (status) 

ここで pthread_exit スレッドを明示的に終了するために使用されます。通常、pthread_exit() ルーチンは、スレッドが作業を完了し、存在する必要がなくなった後に呼び出されます。

main() が作成したスレッドの前に終了し、pthread_exit() で終了した場合、他のスレッドは引き続き実行されます。それ以外の場合、main() が終了すると自動的に終了します。

この簡単なコード例は、pthread_create() ルーチンで 5 つのスレッドを作成します。各スレッドは「Hello World!」を出力します。メッセージを送信し、pthread_exit() の呼び出しで終了します。

#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

void *PrintHello(void *threadid) {
   long tid;
   tid = (long)threadid;
   cout << "Hello World! Thread ID, " << tid << endl;
   pthread_exit(NULL);
}

int main () {
   pthread_t threads[NUM_THREADS];
   int rc;
   int i;
   
   for( i = 0; i < NUM_THREADS; i++ ) {
      cout << "main() : creating thread, " << i << endl;
      rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);
      
      if (rc) {
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

次のように -lpthread ライブラリを使用して次のプログラムをコンパイルします −

$gcc test.cpp -lpthread

ここで、次の出力を与えるプログラムを実行します-

main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Hello World! Thread ID, 0
Hello World! Thread ID, 1
Hello World! Thread ID, 2
Hello World! Thread ID, 3
Hello World! Thread ID, 4

引数をスレッドに渡す

この例は、構造体を介して複数の引数を渡す方法を示しています。次の例で説明するように、void を指すため、スレッド コールバックで任意のデータ型を渡すことができます −

#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

struct thread_data {
   int  thread_id;
   char *message;
};

void *PrintHello(void *threadarg) {
   struct thread_data *my_data;
   my_data = (struct thread_data *) threadarg;

   cout << "Thread ID : " << my_data->thread_id ;
   cout << " Message : " << my_data->message << endl;

   pthread_exit(NULL);
}

int main () {
   pthread_t threads[NUM_THREADS];
   struct thread_data td[NUM_THREADS];
   int rc;
   int i;

   for( i = 0; i < NUM_THREADS; i++ ) {
      cout <<"main() : creating thread, " << i << endl;
      td[i].thread_id = i;
      td[i].message = "This is message";
      rc = pthread_create(&threads[i], NULL, PrintHello, (void *)&td[i]);
      
      if (rc) {
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

上記のコードをコンパイルして実行すると、次の結果が生成されます −

main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Thread ID : 3 Message : This is message
Thread ID : 2 Message : This is message
Thread ID : 0 Message : This is message
Thread ID : 1 Message : This is message
Thread ID : 4 Message : This is message

スレッドの結合と切り離し

スレッドを結合または切り離すために使用できる次の 2 つのルーチンがあります −

pthread_join (threadid, status) 
pthread_detach (threadid) 

pthread_join() サブルーチンは、指定された「threadid」スレッドが終了するまで呼び出しスレッドをブロックします。スレッドが作成されると、その属性の 1 つで、結合可能か分離可能かが定義されます。結合可能として作成されたスレッドのみ結合できます。スレッドが切り離された状態で作成された場合、スレッドを結合することはできません。

この例は、Pthread 結合ルーチンを使用してスレッドの完了を待機する方法を示しています。

#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>

using namespace std;

#define NUM_THREADS 5

void *wait(void *t) {
   int i;
   long tid;

   tid = (long)t;

   sleep(1);
   cout << "Sleeping in thread " << endl;
   cout << "Thread with id : " << tid << "  ...exiting " << endl;
   pthread_exit(NULL);
}

int main () {
   int rc;
   int i;
   pthread_t threads[NUM_THREADS];
   pthread_attr_t attr;
   void *status;

   // Initialize and set thread joinable
   pthread_attr_init(&attr);
   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

   for( i = 0; i < NUM_THREADS; i++ ) {
      cout << "main() : creating thread, " << i << endl;
      rc = pthread_create(&threads[i], &attr, wait, (void *)i );
      if (rc) {
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }

   // free attribute and wait for the other threads
   pthread_attr_destroy(&attr);
   for( i = 0; i < NUM_THREADS; i++ ) {
      rc = pthread_join(threads[i], &status);
      if (rc) {
         cout << "Error:unable to join," << rc << endl;
         exit(-1);
      }
      cout << "Main: completed thread id :" << i ;
      cout << "  exiting with status :" << status << endl;
   }

   cout << "Main: program exiting." << endl;
   pthread_exit(NULL);
}

上記のコードをコンパイルして実行すると、次の結果が生成されます −

main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Sleeping in thread
Thread with id : 0 .... exiting
Sleeping in thread
Thread with id : 1 .... exiting
Sleeping in thread
Thread with id : 2 .... exiting
Sleeping in thread
Thread with id : 3 .... exiting
Sleeping in thread
Thread with id : 4 .... exiting
Main: completed thread id :0  exiting with status :0
Main: completed thread id :1  exiting with status :0
Main: completed thread id :2  exiting with status :0
Main: completed thread id :3  exiting with status :0
Main: completed thread id :4  exiting with status :0
Main: program exiting.

C言語

  1. C++ 演算子
  2. C++ コメント
  3. C++ クラス テンプレート
  4. C++ の概要
  5. C++ 定数/リテラル
  6. C++ の演算子
  7. C++ の数値
  8. C++ リファレンス
  9. C++ テンプレート
  10. C++ マルチスレッド
  11. C# - マルチスレッド