サンプル集  >  LinuxC  >  pthreadC
pthreadC
2005/05/08

3つのスレッドを生成し、全てのスレッドの終了を待ちます。

◆環境
OS Linux 2.6.9-5.0.3.EL
gcc 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)

メインです。

LC004_main.c
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
/* 2005/04/04 (c) ymlib.com */
/* 3つのスレッドを生成し、全てのスレッドの終了を待つ */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

extern void* myThread( void* );

int main( int argc, char** argv )
{
    pthread_t tid[3];
    int       ret = 0;
    int       i;

    printf( "LC004_main start!!\n" );

    /* 3つのスレッドを生成 */
    for ( i = 0; i < 3; i++ )
    {
        ret = pthread_create( &tid[i], NULL, myThread, NULL );
        if ( ret != 0 )
        {
            /* スレッド生成失敗 */
            printf( "pthread_create failed!!=[%d]\n", ret );
            exit( -1 );
        }

        printf( "thread ID=[%ld]\n", tid[i] );
    }

    /* 3つのスレッドの終了を待つ */
    for ( i = 0; i < 3; i++ )
    {
        pthread_join( tid[i], NULL );
    }

    printf( "LC004_main end!!\n" );

    return( 0 );
}

スレッドで動く関数です。 printfでメッセージを表示し3秒待ち、またメッセージを表示し終了します。

LC004_threadMain.c
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
/* 2005/04/04 (c) ymlib.com */
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <pthread.h>

void* myThread( void* pParam )
{
    struct timeval tv;

    int r = 0;

    /* 休止秒数を取得                       */
    /* 乱数っぽくなるよう、マイクロ秒を取得 */
    gettimeofday( &tv, 0x00 );
    r = tv.tv_usec % 5;

    printf( "My Thread start!![%d]\n", r );

    /* 休止 */
    sleep( r );

    printf( "My Thread end!![%d]\n", r );

    /* スレッド終了 */
    pthread_exit( 0 );
}

メイクファイルです。

makefile
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
# 2005/04/04 (c) ymlib.com
TARGET = LC004
OBJS = LC004_main.o        \
       LC004_threadMain.o
CC = /usr/bin/gcc

$(TARGET): $(OBJS)
        $(CC) -o $@ $(OBJS) -lpthread
.SUFFIXES: .c.o
.c.o:
        $(CC) -Wall -c $<

clean:
        rm -f $(TARGET) $(OBJS)

◆実行結果
$ ./LC004
LC004_main start!!
thread ID=[2305843009227354752]
thread ID=[2305843009237840512]
thread ID=[2305843009248326272]
My Thread start!![4]
My Thread start!![3]
My Thread start!![2]
My Thread end!![2]
My Thread end!![3]
My Thread end!![4]
LC004_main end!!

$ ./LC004
LC004_main start!!
thread ID=[2305843009227354752]
thread ID=[2305843009237840512]
thread ID=[2305843009248326272]
My Thread start!![0]
My Thread end!![0]
My Thread start!![3]
My Thread start!![1]
My Thread end!![1]
My Thread end!![3]
LC004_main end!!

▲ PageTop  ■ Home


Copyright (C) 2013 ymlib.com