pthread 1つのスレッドを動かす

提供: C言語入門
移動: 案内検索
スポンサーリンク

C言語のpthreadを使用して、スレッドを1つ作成し、スレッドの終了を待ちます。pthread_createでスレッドの作成・実行を行い、pthread_joinでスレッドの終了を待ちます。

概要

pthreadでスレッドを作成するには、pthread_createを使用します。 pthread_createの引数は、以下の通りです。

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

第3引数には、スレッドで実行する関数を渡します。

スレッドの終了を待つには、pthread_joinを使用します。

int
pthread_join(pthread_t thread, void **value_ptr);
forkとpthread
動作 forkモデル スレッドモデル
プロセス・スレッドの作成 fork pthread_create
プロセス・スレッドの終了を待つ wait,waitpid, wait4 pthread_join

pthread_createをしたらpthread_joinするかpthread_detachする

pthread_createでスレッドを作成した場合、joinもしくは、detachしなければなりません。 pthread_detachは、メインスレッドからスレッドを切り離す機能を提供します。

pthread_createで作ったスレッドが終了したとき、joinで終了を回収せずに、pthread_createだけを呼び出して、プログラムを動かしているとメモリリークします。

pthread1.c の例

この例で、joinせずにmainが終わるとpthread_createのスレッドの終了をまたずに、プログラム(スレッドも含め)が終了します。

ソースコード pthread1.c

#include <stdio.h>
#include <pthread.h>
#include <err.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
 
void f1(void);
 
int
main(void)
{
        pthread_t thread1;
        int ret1;
 
        ret1 = pthread_create(&thread1,NULL,(void *)f1,NULL);
        if (ret1 != 0) {
                err(EXIT_FAILURE, "can not create thread 1: %s", strerror(ret1) );
        }
 
        printf("execute pthread_join\n");
        ret1 = pthread_join(thread1,NULL);
        if (ret1 != 0) {
                errc(EXIT_FAILURE, ret1, "can not join thread 1");
        }
        printf("join\n");
        return 0;
}
 
void
f1(void)
{
        size_t i;
 
        for(i=0; i<4; i++){
                printf("Doing one thing\n");
        }
}

コンパイル

cc  -lpthread pthread1.c -o pthread1

実行例

% ./pthread1
execute pthread_join
Doing one thing
Doing one thing
Doing one thing
Doing one thing
join

関連項目




スポンサーリンク