Linux C多线程

来源:互联网 发布:打印文件软件 编辑:程序博客网 时间:2024/06/07 00:34

一个简单的Linux C多线程程序:主线程创建启动了2个子线程,通过pthread_join等待子线程结束。

#include <stdio.h>#include <pthread.h>#include <unistd.h>#define NUM 5int 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

原创粉丝点击