1. 程式人生 > >Linux下C語言多程序實現

Linux下C語言多程序實現

這是一個簡單的例子

#include <stdio.h>

#include <pthread.h>  
//thread函式是開的一個程序實現的功能
void thread(void){
        int i;
        for(i=0;i<3;i++)
                printf("this is a thread\n");
}       

int main(){
        pthread_t id;  //定義一個pthread_t型別的變數
        int i,ret;
        ret = pthread_create(&id,NULL,(void*)thread,NULL);    //建立一個程序,成功的話返回0
        if(ret!=0){
                printf("shibai");
        }
        for(i=0;i<3;i++)
                printf("this is main thread\n");
        pthread_join(id,NULL);   //這個函式是等待一個程序的結束,也就是保證開的程序要實現完成
        return (0);
}

編譯

gcc test.c -lpthread  -o test