C fork dealing with global variable

前端 未结 5 1180
谎友^
谎友^ 2021-01-05 01:37

I\'m not understanding the output of this program:

#include 
#include 
#include 

int i = 0;

int main()
{
           


        
5条回答
  •  迷失自我
    2021-01-05 01:54

    Try using pthreads if you want to create a thread inside the process for concurrent programming. The function you want is pthread_create and pthread_join for tidying up later.

    Something like this:

    #include 
    #include 
    #include 
    #include 
    
    
    int i = 0;
    
    void *threadFunc(void *arg) 
    {
        printf("%d\n",i);
    }
    
    int main()
    {
        int j = 0;  
        int returnValue = 0;
        pthread_t* myThread = (pthread_t*) calloc(3, sizeof(pthread_t));;
    
        while(i < 3)
        {
    
            returnValue = pthread_create(&myThread[i], NULL, threadFunc, NULL);
            printf("main thread: %d\n",i);
            i++;
    
        }
    
    
        for(j = 0; j < 3; j++)
        {
            pthread_join(myThread[j], NULL); 
    
        }
    
        return 0;
    }
    

    But perhaps not, depending on your actual needs.

提交回复
热议问题