您的位置:首页 > 编程语言 > C语言/C++

一起talk C栗子吧(第八十回:C语言实例--进程互斥)

2015-12-22 22:36 375 查看
各位看官们,大家好,上一回中咱们说的是父进程与子进程的例子,这一回咱们说的例子是:进程互斥。闲话休提,言归正转。让我们一起talk C栗子吧!

我们在上一回中介绍了父进程与子进程的例子,这一回,我们说的是进程之间的互斥。所谓的互斥就是指两个进程按照一定的顺序使用临界资源。比如键盘就是一种临界资源。如果父进程在使用的时候,子进程需要等待,直到父进程使用完后,它才能使用。接下来,我们通过一个实际的例子进行说明:

[code]int main()
{
    pid_t pid;
    pid_t pid_res;
    int count = 0;
    int stat_value;

    pid = fork();

    if(pid > 0)
    {
        printf("PID: %d -> Father Process is running \n",getpid());
        count++;
        printf("count is %d in Father Process \n",count);
    }
    else if(pid == 0)
    {
        printf("PID: %d -> Son Process is running \n",getpid());
        count++;
        printf("count is %d in Son Process \n",count);
    }
    else
    {
        printf("Create process failed \n");
        return 1;
    }

    return 0;
}


我们把编译上面的代码并且运行,可以得到以下结果:

[code] ./s                                   //运行编译后的程序
PID: 3030 -> Father Process is running 
count is 1 in Father Process           //父进程在使用count这种临界资源
PID: 3031 -> Son Process is running 
count is 1 in Son Process              //子进程在使用count这种临界资源


在上面的代码中,我们使用count模仿临界资源,从程序的运行结果可以看到,父进程和子进程,对count的使用没有任何联系,它们几乎是同时使用该临界资源,没有一定的顺序。(当然,count在程序中不是真正的临界资源,我们只是在模仿)。

如果想让进程之间按照一定的顺序使用临界资源,那么可以使用wait函数。它通常在父进程中使用,在父进程中使用wait函数后,它会一直等待子进程运行,直到子进程运行结束了,它才开始运行父进程中的内容。下面是我们使用wait后的代码:

[code]int main()
{
    pid_t pid;
    pid_t pid_res;
    int count = 0;
    int stat_value;

    pid = fork();

    if(pid > 0)
    {
        printf("PID: %d -> Father Process is running \n",getpid());
        pid_res = wait(&stat_value);         //使用wait函数实现进程互斥

        if(pid_res > 0)                      //等待子进程结束后,再使用临界资源
        {
            printf("Son process finished: PID = %d \n",pid_res);
            count++;
            printf("count is %d in Father Process \n",count);
        }
    }
    else if(pid == 0)
    {
        printf("PID: %d -> Son Process is running \n",getpid());
        count++;
        printf("count is %d in Son Process \n",count);
    }
    else
    {
        printf("Create process failed \n");
        return 1;
    }

    return 0;
}


下面是程序的运行结果,请大家和没有使用wait函数的运行结果进程对比。

[code] ./s                                     //运行编译后的程序
PID: 3073 -> Father Process is running   //父进程没有使用count这种临界资源
PID: 3074 -> Son Process is running      
count is 1 in Son Process                //子进程在使用count这种临界资源
Son process finished: PID = 3074         //子进程结束
count is 1 in Father Process             //父进程在使用count这种临界资源


看官们,正文中就不写代码了,详细的代码放到了我的资源中,大家可以点击这里下载使用。

各位看官,关于进程互斥的例子咱们就说到这里。欲知后面还有什么例子,且听下回分解。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: