剛才寫了一個簡單的多執行序程式....記錄一下
#include <stdio.h>
#include <pthread.h>
void* thread0(void*);
void* thread1(void*);
int main(void) {
void* result;
pthread_t t0;
pthread_t t1;
pthread_create(&t0, NULL, thread0, NULL);
pthread_create(&t1, NULL, thread1, NULL);
/* wait for thread terminate */
pthread_join(t0, &result);
pthread_join(t1, &result);
return 0;
}
void* thread0(void *argu) {
int i = 0;
for (; i<5; i++) {
printf("thread0: %d\n", i);
sleep(1);
}
return NULL;
}
void* thread1(void *argu) {
int i = 0;
for (; i<10; i++) {
printf("thread1: %d\n", i);
sleep(1);
}
return NULL;
}
ps. Compile 時需要加上 -lpthread --> gcc a.c -lthread
執行結果:
./a.out
thread1: 0
thread0: 0
thread1: 1
thread0: 1
thread1: 2
thread0: 2
thread1: 3
thread0: 3
thread1: 4
thread0: 4
thread1: 5
thread1: 6
thread1: 7
thread1: 8
thread1: 9
延伸閱讀:
2. Linux下的多線程編程

請先 登入 以發表留言。