[国嵌攻略][084][信号同步编程]
生活随笔
收集整理的這篇文章主要介紹了
[国嵌攻略][084][信号同步编程]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
進程同步
一組并發進程進行相互合作、相互等待,使得各進程按一定的順序執行的過程稱為進程間的同步。
?
進程同步與進程互斥
進程同步問題的關鍵在于生產者不需要獲取信號量,消費者不需要釋放信號量,所以信號量的初值設置為0。但是進程互斥問題中雙方都需要獲取和釋放信號量,所以信號量的初值至少為1。
?
producor.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;fd = open("product.txt", O_RDWR | O_CREAT, 0777);//睡眠等待sleep(10);//寫入數據write(fd, "The product is finished!", 25);//關閉文件 close(fd);//創建信號量int key;int semid;key = ftok("product.txt", 0);semid = semget(key, 1, IPC_CREAT);//設置信號量semctl(semid, 0, SETVAL, 0); //設置信號量0的值為0//釋放信號量struct sembuf sops;sops.sem_num = 0;sops.sem_op = 1;sops.sem_flg = SEM_UNDO;semop(semid, &sops, 1); }?
customer.c
#include <stdlib.h>#include <sys/ipc.h> #include <sys/sem.h>void main(){//打開信號量int key;int semid;key = ftok("product.txt", 0);semid = semget(key, 1, IPC_CREAT);//獲取信號量struct sembuf sops;sops.sem_num = 0;sops.sem_op = -1;sops.sem_flg = SEM_UNDO;semop(semid, &sops, 1);//拷貝文件system("cp product.txt ship.txt"); }?
轉載于:https://www.cnblogs.com/d442130165/p/5225409.html
總結
以上是生活随笔為你收集整理的[国嵌攻略][084][信号同步编程]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Activity(二)
- 下一篇: 耦合度和聚合度