Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <semaphore.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include "lib.h"
- #include <time.h>
- typedef struct{
- int muzi;
- int zeny;
- sem_t fmuzi;
- sem_t fzeny;
- sem_t m;
- sem_t dot;
- }DATA;
- DATA *data;
- void muz(int i){
- sem_wait(&data->m);
- if(data->zeny > 0){
- data->zeny--;
- sem_post(&data->fzeny);
- }else{
- data->muzi++;
- sem_post(&data->m);
- sem_wait(&data->fmuzi);
- }
- sem_wait(&data->dot);
- printf("tanec muz\n");
- sem_post(&data->m);
- }
- void zena(int i){
- sem_wait(&data->m);
- if(data->muzi > 0){
- data->muzi--;
- sem_post(&data->fmuzi);
- }else{
- data->zeny++;
- sem_post(&data->m);
- sem_wait(&data->fzeny);
- }
- sem_post(&data->dot);
- printf("tanec zena\n");
- }
- int main(){
- data = (DATA*) malloc_shared(sizeof(DATA));
- if(data == NULL){
- perror("malloc shared \n");
- exit(-1);
- }
- int mcnt = rand()%10 + 5;
- int wcnt = rand()%10 + 5;
- int i;
- data->muzi = 0;
- data->zeny = 0;
- sem_init(&data->fmuzi, 1 , 0);
- sem_init(&data->fzeny, 1 , 0);
- sem_init(&data->m, 1 , 1);
- sem_init(&data->dot, 1 , 0);
- srand(time(NULL));
- for(i = 0; i < mcnt; i++){
- switch(fork()){
- case 0:
- muz(i);
- return 0;
- case -1:
- perror("fork muz \n");
- exit(-1);
- default:
- break;
- }
- }
- for(i = 0; i < wcnt; i++){
- switch(fork()){
- case 0:
- zena(i);
- return 0;
- case -1:
- perror("fork muz \n");
- exit(-1);
- default:
- break;
- }
- }
- for(i = 0; i < wcnt + mcnt; i++){
- wait(NULL);
- }
- free_shared(data);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement