スレッド例題

スレッドという言葉を聞き慣れない方もいらっしゃるかもしれませんが、ここでの説明は省略します。しかし、今回のプログラムの動作を見ていただければ、スレッドというものがどういうものか?と言うのが多少分かってもらえるかも知れません。

スレッド例題(list_17.c)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pthread.h>    /* for POSIX thread */

int i=0;

void* prfunc(void* arg)
{
    for(;;) {
        i++;
        usleep(100);
    }
}

int main()
{
    int pstatus;
    pthread_t thread_n;

    pstatus = pthread_create(&thread_n,NULL,prfunc,(void *)NULL);
    if(pstatus!=0){
        fprintf(stderr,"pthread_create:%s\n",strerror(pstatus));
        exit(-1);
    }
    for(;i<100;){
        printf("%d\n",i);
    }
    return 0;
}
実行結果
Gami[962]% list_17.exe
0
0
0
16
16
16
34
34
34
52
52
52
70
70
70
88
88
88
Gami[963]%
inserted by FC2 system