制片人/ Consumer_problem(信号量)

时间:2018-01-08 21:41:40

标签: c++ linux fork semaphore

所以我有使用信号量解决生产者 - 消费者问题的任务。我必须有FIFO缓冲区和选项连续多次推/弹相同的项目。 我应该使用fork()函数测试它来创建一个新进程。 问题是,当我尝试使用一个项目时,它会停留在wait()函数

有我的代码:

#include <cstdlib>
#include <iostream>
#include <string>
#include <pthread.h>
#include <ctime>
#include <mutex>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>

using namespace std;


mutex wrt,rd,ks;
int buffer[100];
sem_t sem_in,sem_out;
int n, lo, hi;

void produce(int repeat)
{
    cout<<"IN produce after paramiters"<< repeat <<endl;
    int item;
    item = rand()%100 + 1;
    wrt.lock();
    ks.lock();
            for(int i=0; i<repeat; i++)
            {
                if(n != 100){sem_wait(&sem_in);}
                else{ks.unlock(); sem_wait(&sem_in); ks.lock();}
                buffer[hi] = item;
                hi = (hi + 1) % 100;        //ring buffer
                n = n +1;         //one more item in buffer
                cout<< "Item: "<< item << " Was prodused n = " << n << endl;
                sem_post(&sem_out);
            }
    ks.unlock();
    wrt.unlock();

}

void consume(int repeat)
    {
        cout<<"IN consume after paramiters"<< repeat <<endl;
        rd.lock();
        ks.lock();
            for(int i=0; i<repeat; i++)
            {
                if(n != 0){sem_wait(&sem_out);}
                else{ks.unlock(); sem_wait(&sem_out); ks.lock();}
                int val;
                val = buffer[lo];
                lo = (lo + 1) % 100;
                n -= 1;
                cout<< "Item: "<< val << " Was removed n = " << n << endl;
                sem_post(&sem_in);
            }
        ks.unlock();
        rd.unlock();
    }

int main()
{
    n = 0;
    lo = 0;
    hi = 0;
    srand(time(0));
      pid_t pid;
  int rv = 5;
  sem_init(&sem_in,0,100);
  sem_init(&sem_out,0,0);
  int repeat;
  pid = clone(sem_in,sem_out, n, lo, hi);
  switch(pid) {
  case -1:
          perror("fork"); 
          exit(1); 
  case 0:
          printf(" CHILD: PID -- %d\n", getpid());
          printf(" CHILD: PID parent -- %d\n", getppid());
          repeat = rand()%200 + 1;
          consume(repeat);
          exit(rv);
  default:
          printf("PARENT: PID -- %d\n", getpid());
          printf("PARENT: PID child %d\n",pid);
          repeat = rand()%200 + 1;
          produce(repeat);
          wait();
  }
}

0 个答案:

没有答案