A problem with shared process variables

/*thread.c*/
#include <stdio.h>
#include <pthread.h>


/*Thread 1*/
void thread_1(void)
{
    int i=0;
    for(i=0;i<=6;i++ )
    {
        printf("This is a pthread_1.\n");
        if(i==2)
            pthread_exit(0); //Use pthread_exit() to call the return value of the thread to exit the thread, but the exit thread occupies The resources will not be released when the thread terminates
        sleep(1);
    }
}


/*Thread 2*/
void thread_2(void)
{
    int i;
    for(i=0;i<3;i++)
        printf("This is a pthread_2.\n");         
    pthread_exit(0); //Use pthread_exit() to call the return value of the thread to exit the thread, but the resources occupied by the exit thread will not be released with the termination of the thread
}


int main(void)
{
    pthread_t id_1,id_2;
    int i,ret;
/*创建线程一*/
    ret=pthread_create(&id_1,NULL,(void  *) thread_1,NULL);
    if(ret!=0)
    {
        printf("Create pthread error!\n");
    return -1;
    }
/*创建线程二*/
     ret=pthread_create(&id_2,NULL,(void  *) thread_2,NULL);
    if(ret!=0)
    {
        printf("Create pthread error!\n");
    return -1;
    }
/*等待线程结束*/
    pthread_join(id_1,NULL);
    pthread_join(id_2,NULL);
    return 0;

}


The code result is shown in the figure, which is quoted from others:

https://blog.csdn.net/youbang321/article/details/7816016

I guess: Since the two variables i in thread 1 and thread 2 are local variables, they are stored in different storage areas (this may be wrong, please criticize and correct)

My personal understanding is that after the first thread_1 is executed once, due to thread_1sleep, i_1=0 at this time.

The system switches to thread_2 for execution. Since thread_2 is executed until the end, the thread exits after 3 times of output, at this time i_2=4.

Then continue to execute thread_1, exit when i_1==2, and output twice at this time. After exit, the value of i_1 is still equal to 2.

Then the join function executes the function of thread_1 and executes it once

The thread_2 function is not executed because the conditional judgment fails.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324800448&siteId=291194637