共享进程变量的一个问题

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


/*线程一*/
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);                      //用pthread_exit()来调用线程的返回值,用来退出线程,但是退出线程所占用的资源不会随着线程的终止而得到释放
        sleep(1);
    }
}


/*线程二*/
void thread_2(void)
{
    int i;
    for(i=0;i<3;i++)
        printf("This is a pthread_2.\n");         
    pthread_exit(0);                              //用pthread_exit()来调用线程的返回值,用来退出线程,但是退出线程所占用的资源不会随着线程的终止而得到释放
}


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;

}


代码结果如图,这是引用别人的:

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

我猜 :由于线程1和线程2中两个变量i是局部变量,存储在不用的存储区域(这可能有错,请批评指正)

我个人的理解是第一个线程_1在在执行了一次以后,由于线程_1sleep,这时i_1=0。

系统切换到线程_2执行,由于线程_2一直执行到结束,输出3次后线程退出,此时i_2=4.

然后继续执行线程_1,当i_1==2时候退出,此时又输出了两次。退出后i_1的值依然等于2.

然后join函数执行线程_1的函数,执行1次

线程_2函数由于条件判断不通过而不执行。

猜你喜欢

转载自blog.csdn.net/q305925523/article/details/80050695