zoukankan      html  css  js  c++  java
  • 信号量进程同步,王明学learn

                  信号量进程同步

      一组并发进程进行互相合作、互相等待,使得各进程按一定的顺序执行的过程称为进程间的同步。

      信号量在进程同步时初始值为:0

         信号量在进程互斥时初始值为:大于0的

    本章节主要使用信号量,使的两个进程生产消费有序的完成。就是说必须等到生产完全完场才能,让消费执行。

    下面进入编程语言编程学习:

     1.首先创建文件product.c文件------>vim  product.c

    编写代码如下:

    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <unistd.h>
    
    #include <sys/ipc.h>
    #include <sys/sem.h>
    
    void main()
    {
        int fd;
        key_t key;
        int semid;
        struct sembuf sops;
        key = ftok("/root",2); //创建键值
    
        //创建信号量集合
        semid = semget(key, 1, IPC_CREAT);
        semctl(semid,0,SETVAL,0);  //设置信号量的值为0
    /*****************生产者创建文件**************************/
        //1.创建产品~文件
        fd = open("./product.txt",O_RDWR|O_CREAT,0775);
        
        //2.休息
        sleep(20);
        
        //向产品文件填入内容
        write(fd,"the product is finished!",25);
        close(fd);
    
        //释放信号量
        sops.sem_num = 0;
        sops.sem_op = 1;
        sops.sem_flg = SEM_UNDO;
        semop(semid,&sops, 1);
    }

     使用linux中的编译器编译,gcc product.c -o product

    2.接下来创建customer.c------------->vim customer.c

    编辑文件为:

    #include <stdlib.h>
    
    #include <sys/ipc.h>
    #include <sys/sem.h>
    void main()
    {
         key_t key;
         int semid;
         struct sembuf sops;
    
         key = ftok("/root",2); //创建键值
    
        //打开信号量集合
         semid = semget(key, 1, IPC_CREAT);
    
        //获取信号量
         sops.sem_num = 0;
         sops.sem_op = -1;
         sops.sem_flg = SEM_UNDO;
         semop(semid,&sops, 1);
    
         system("cp ./product.txt ./ship/");
    }

     同样对customer.c进行编译------->gcc customer.c -o customer

    2.下面进入代码运行

    1).运行product------->./product

    2).运行customer------->./customer

      可以看到当product为执行完成时customer进程移植处于等待状态,知道product运行结束,customer进程才紧接着完成。当然也可以看到之前已经创建的ship文件下面有一个product.txt文件,而且里面已经有the product is finished!这句话。

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

  • 相关阅读:
    前端JS 4
    前端JS 3
    前端JS 2
    前端JS 1
    JS的知识补丁
    去除inline-block元素间的空隙
    js中“||”和“&&”的高级用法
    WebAPP-1
    Node.js_1
    click和onclick的区别
  • 原文地址:https://www.cnblogs.com/wmx-learn/p/5303131.html
Copyright © 2011-2022 走看看