Cplusplus-cpp-multithreading

提供:Dev Guides
移動先:案内検索

C ++マルチスレッド

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

プロセスベースのマルチタスクは、プログラムの同時実行を処理します。 スレッドベースのマルチタスクは、同じプログラムの各部分の同時実行を処理します。

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

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

このチュートリアルでは、Linux OSで作業しており、POSIXを使用してマルチスレッドC ++プログラムを作成することを想定しています。 POSIX Threads、または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 Parameter & Description
1

thread

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

2

attr

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

3

start_routine

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

4

arg

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.