pthread_create和pthread_join使用例子,将下面的代码保存到thread.c中,
-
#include <pthread.h>
-
#include <stdlib.h>
-
#include <unistd.h>
-
#include <stdio.h>
-
void *thread_function(void *arg) {
-
int i;
-
for ( i=0; i<20; i++) {
-
printf("Thread says hi!\n");
-
sleep(1);
-
}
-
return NULL;
-
}
-
int main(void) {
-
pthread_t mythread;
-
-
if ( pthread_create( &mythread, NULL, thread_function, NULL) ) {
-
printf("error creating thread.");
-
abort();
-
}
-
if ( pthread_join ( mythread, NULL ) ) {
-
printf("error joining thread.");
-
abort();
-
}
-
exit(0);
-
}
用
gcc thread.c -o thread.o -pthread编译生成thread.o
[chenyun]$
gcc thread.c -o thread.o -pthread
执行thread.o:
[chenyun]$
./thread.o
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
[chenyun]$
阅读(4986) | 评论(0) | 转发(0) |