生产者消费者进程互斥问题
用C++模拟实现生产者消费者,结果加了mutex以后,只有当生产者把缓冲区填满消费者才去消费,反之亦然。不知道是哪里出的错
代码应该没问题吧
生产者部分:
WaitForSingleObject(shmem->emptySem, INFINITE);
WaitForSingleObject(shmem->mutex, INFINITE);
。。。
ReleaseMutex(shmem->mutex);
ReleaseSemaphore(shmem->fullSem, 1, NULL);
消费者部分:
WaitForSingleObject(shmem->fullSem, INFINITE);
WaitForSingleObject(shmem->mutex, INFINITE);
。。。
ReleaseMutex(shmem->mutex);
ReleaseSemaphore(shmem->emptySem, 1, NULL);
[解决办法]
只有当生产者把缓冲区填满消费者才去消费,反之亦然??? 上面的代码有问题
signal(SIGSUR1,SIGIGN);signal(SIGSUR2,SIGIGN);producer进程: while(1){ while(((in+1)%BUFFER_SIZE)==out{ kill(consumer_pid,SIGSUR2); pause; } buffer[in]=nextProduced; in=(in+1)%BUFFER_SIZE;}consumer进程: while(1){ while(in==out){ kill(producer_pid,SIGSUR2); pause; } nextConsumed=buffer[out]; out=(out+1)%BUFFER_SIZE;}
[解决办法]
上面的while(((in+1)%BUFFER_SIZE)==out 和 while(in==out) 将while改成if 不好意思哈