pthreads (2) 超基本から

pthreadsまとめ。まずは基本から。

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

#define THREADSNUM 5
void func(int *);

int main(void){
     pthread_t thread[THREADSNUM];
     int i;
     for(i=0; i<THREADSNUM; i++){
          pthread_create(&thread[i], NULL, (void *)func, &i);
     }
     for(i=0; i<THREADSNUM; i++){
          pthread_join(thread[i], NULL);
     }
     printf("end\n");
     return 0;
}
void func(int *n)
{
     int i, nn=*n;
     for(i=0; i<5; i++){
          printf("thread %d\n", nn);
          usleep(1);
     }
}
thread 0
thread 1
thread 2
thread 3
thread 4
thread 0
thread 1
thread 2
thread 3
thread 4
thread 0
thread 1
thread 2
thread 3
thread 4
thread 0
thread 1
thread 2
thread 3
thread 4
thread 0
thread 1
thread 2
thread 3
thread 4
end

pthread_create()でスレッド作成。Javaと違って、ここで作成された関数が実行されます。pthread_join()を実行すると、ここで指定したスレッドの終了を待ちます。ここでは全てのスレッドが終了するのを待っているので、全て終了した後"end"がでるということになっています。

int pthread_create(pthread_t * thread, pthread_attr_t * attr, 
                   void * (*start_routine)(void *), void * arg);

start_routineはスレッドで実行したいサブルーチンへのポインタ、argはサブルーチンへの引数。どうやら可変ではないらしいので、複数の値を渡したいときは構造体にパックする必要があるかも。

int pthread_join(pthread_t th, void **thread_return);

thread_returnpには、thread_exit()のステータスが入る・・・っぽい。