サンプル集  >  LinuxC  >  pthread@
pthread@
2005/05/08

pthread_create()関数でスレッドを生成し、pthread_join()関数でスレッドの終了を待ちます。

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

メインです。

LC001_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: 
/* 2005/04/04 (c) ymlib.com */
/* pthread_createでスレッドを生成し、スレッドの終了を待つ */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

extern void* myThread( void* );

int main( int argc, char** argv )
{
    pthread_t tid = 0x00;
    int       ret = 0;

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

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

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

    /* スレッドの終了を待つ */
    pthread_join( tid, NULL );

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

    return( 0 );
}

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

LC001_threadMain.c
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
/* 2005/04/04 (c) ymlib.com */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

void* myThread( void* pParam )
{
    printf( "My Thread start!!\n" );

    /* 休止 */
    sleep( 3 );

    printf( "My Thread end!!\n" );

    /* スレッド終了 */
    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 = LC001
OBJS = LC001_main.o        \
       LC001_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)

◆実行結果
$ ./LC001
LC001_main start!!
thread ID=[2305843009227354752]
My Thread start!!
My Thread end!!
LC001_main end!!


2013/11/25 追記

次の環境でも正常にメイク、実行できました。

OS Linux obsax3 3.0.6 #1 SMP Thu Mar 7 19:14:19 JST 2013 armv7l GNU/Linux
gcc 4.4.5 (Debian 4.4.5-8)

◆実行結果
# ./LC001
LC001_main start!!
thread ID=[1085404272]
My Thread start!!
My Thread end!!
LC001_main end!!

▲ PageTop  ■ Home


Copyright (C) 2013 ymlib.com