C++ マルチスレッド


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

  • プロセスベースのマルチタスクは、プログラムの同時実行です。

  • スレッドベースのマルチタスクは、同じプログラムの断片を同時に実行することです。

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

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

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

スレッドの作成

POSIX スレッドの作成に使用できる次のプログラム:

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

ここで、pthread_create は新しいスレッドを作成し、実行可能にします。以下にパラメータの説明を示します。

パラメータ 説明
thread スレッド識別子ポインタを指します。
attrスレッド属性の設定に使用できる不透明な属性オブジェクト。スレッド プロパティ オブジェクトを指定することも、デフォルト値の NULL を使用することもできます。
start_routineスレッド実行関数の開始アドレス。スレッドが作成されると実行されます。
arg関数を実行するための引数。参照を void 型へのポインタとしてキャストして渡す必要があります。パラメータが渡されない場合は、NULL が使用されます。

スレッドの作成に成功すると、関数は 0 を返します。戻り値が 0 でない場合は、スレッドの作成に失敗したことを意味します。

スレッドの終了

次のプログラムを使用すると、POSIX スレッドを終了することができます:

#include <pthread.h>
pthread_exit (status)

ここでは、pthread_exitを使用してスレッドを明示的に終了します。通常、 pthread_exit() 関数は、スレッドが作業を完了し、存在し続ける必要がなくなったときに呼び出されます。

main() が作成したスレッドより前に終了し、pthread_exit() 経由で終了した場合、他のスレッドは実行を継続します。それ以外の場合、それらは main() の終わりで自動的に終了します。

次の簡単なコード例では、pthread_create() 関数を使用して 5 つのスレッドを作成し、各スレッドが「Hello php!」を出力します。

#include <iostream>
// 必须的头文件是
#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

// 线程的运行函数
void* say_hello(void* args)
{
    cout << "Hello php!" << endl;
}

int main()
{
    // 定义线程的 id 变量,多个变量使用数组
    pthread_t tids[NUM_THREADS];
    for(int i = 0; i < NUM_THREADS; ++i)
    {
        //参数依次是:创建的线程id,线程参数,调用的函数,传入的函数参数
        int ret = pthread_create(&tids[i], NULL, say_hello, NULL);
        if (ret != 0)
        {
           cout << "pthread_create error: error_code=" << ret << endl;
        }
    }
    //等各个线程退出后,进程才结束,否则进程强制结束了,线程可能还没反应过来;
    pthread_exit(NULL);
}

-lpthread ライブラリを使用して、次のプログラムをコンパイルします。

$ g++ test.cpp -lpthread -o test.o

次に、実行します。プログラムを実行すると、次の結果が生成されます:

$ ./test.o
Hello php!
Hello php!
Hello php!
Hello php!
Hello php!

次の簡単なコード例では、pthread_create() 関数を使用して 5 つのスレッドを作成し、受信パラメーターを受け取ります。各スレッドは「Hello php!」メッセージを出力し、受け取ったパラメータを出力し、pthread_exit() を呼び出してスレッドを終了します。

//文件名:test.cpp

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

using namespace std;

#define NUM_THREADS     5

void *PrintHello(void *threadid)
{  
   // 对传入的参数进行强制类型转换,由无类型指针变为整形数指针,然后再读取
   int tid = *((int*)threadid);
   cout << "Hello php! 线程 ID, " << tid << endl;
   pthread_exit(NULL);
}

int main ()
{
   pthread_t threads[NUM_THREADS];
   int indexes[NUM_THREADS];// 用数组来保存i的值
   int rc;
   int i;
   for( i=0; i < NUM_THREADS; i++ ){      
      cout << "main() : 创建线程, " << i << endl;
      indexes[i] = i; //先保存i的值
      // 传入的时候必须强制转换为void* 类型,即无类型指针        
      rc = pthread_create(&threads[i], NULL, 
                          PrintHello, (void *)&(indexes[i]));
      if (rc){
         cout << "Error:无法创建线程," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

ここでプログラムをコンパイルして実行すると、次の結果が生成されます:

$ g++ test.cpp -lpthread -o test.o
$ ./test.o
main() : 创建线程, 0
main() : 创建线程, 1
main() : 创建线程, 2
main() : 创建线程, 3
main() : 创建线程, 4
Hello php! 线程 ID, 4
Hello php! 线程 ID, 3
Hello php! 线程 ID, 2
Hello php! 线程 ID, 1
Hello php! 线程 ID, 0

スレッドにパラメータを渡す

この例では、構造体を介して複数のパラメータを渡す方法を示します。次の例に示すように、スレッド コールバックで 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);
}

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

$ g++ -Wno-write-strings test.cpp -lpthread -o test.o
$ ./test.o
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_join() 関数を使用してスレッドが完了するのを待つ方法を示します。

#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;

   // 初始化并设置线程为可连接的(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], NULL, wait, (void *)i );
      if (rc){
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }

   // 删除属性,并等待其他线程
   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 : 4  ...exiting 
Sleeping in thread 
Thread with id : 3  ...exiting 
Sleeping in thread 
Thread with id : 2  ...exiting 
Sleeping in thread 
Thread with id : 1  ...exiting 
Sleeping in thread 
Thread with id : 0  ...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.