How to “multithread” C code

后端 未结 12 1772
暗喜
暗喜 2020-12-02 09:30

I have a number crunching application written in C. It is kind of a main loop that for each value calls, for increasing values of \"i\", a function that performs some calcul

12条回答
  •  庸人自扰
    2020-12-02 09:45

    You can use pthreads to perform multithreading in C. here is a simple example based on pthreads.

    #include
    #include
    
    void *mythread1();  //thread prototype
    void *mythread2();
    
    int main(){
        pthread_t thread[2];
        //starting the thread
        pthread_create(&thread[0],NULL,mythread1,NULL);
        pthread_create(&thread[1],NULL,mythread2,NULL);
        //waiting for completion
        pthread_join(thread[0],NULL);
        pthread_join(thread[1],NULL);
    
    
        return 0;
    }
    
    //thread definition
    void *mythread1(){
        int i;
        for(i=0;i<5;i++)
            printf("Thread 1 Running\n");
    }
    void *mythread2(){
        int i;
        for(i=0;i<5;i++)
            printf("Thread 2 Running\n");
    }
    

    Reference: C program to implement Multithreading-Multithreading in C

提交回复
热议问题