一个简单的Linux C多线程程序:主线程创建启动了2个子线程,通过pthread_join等待子线程结束。
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define NUM 5
int main(){
pthread_t t1, t2;
void *print_msg(void *);
pthread_create(&t1, NULL, print_msg, (void *)"hello");
pthread_create(&t2, NULL, print_msg, (void *)"world\n");
pthread_join(t1, NULL);
pthread_join(t2, NULL);
}
void *print_msg(void *msg){
int i = 0;
char *out = (char *)msg;
for(i=0; i<NUM; i++){
printf("%s", out);
fflush(stdout);
sleep(2);
}
return NULL;
}
输出:
helloworld
helloworld
helloworld
helloworld
helloworld