标题:生产者和消费者问题。请问为什么输出会嵌套?谢谢
只看楼主
Queenlight
Rank: 1
等 级:新手上路
帖 子:18
专家分:0
注 册:2017-3-14
结帖率:66.67%
已结贴  问题点数:40 回复次数:2 
生产者和消费者问题。请问为什么输出会嵌套?谢谢
#include <iostream>
#include <windows.h>

using namespace std;

#define P(S) WaitForSingleObject(S, INFINITE)
#define V(S) ReleaseSemaphore(S, 1, NULL)
#define Producers 10
#define Consumers 10
typedef HANDLE semaphore;
semaphore mutex, empty, full;

int h = 1;

struct Buffer
{
    int buffer[20];
    int in, out;
} buf;

DWORD WINAPI Produce(LPVOID para)
{
    while(true)
    {
        P(empty);
        P(mutex);
        if((buf.in+1)%20 == buf.out)
        {
            cout << "缓冲区已满,不能再生产" << endl;
            break;
        }
        cout << "生产者生产出一件产品buffer[" << buf.in << "]" << h << endl;
        buf.buffer[buf.in] = h;
        h = (h+1)%20;
        buf.in = (buf.in+1)%20;
        V(mutex);
        V(full);
    }
    return 0;
}

DWORD WINAPI Consum(LPVOID para)
{
    while(true)
    {
        P(full);
        P(mutex);
        if(buf.in == buf.out)
        {
            cout << "缓冲区已空,不能再消费" << endl;
            break;
        }
        cout << "消费者消费了一件产品buffer[" << buf.out << "]" << buf.buffer[buf.out] << endl;
        buf.out = (buf.out+1)%20;
        V(mutex);
        V(empty);
    }
    return 0;
}


int main()
{
    HANDLE hThread[Producers+Consumers];
    DWORD tid;
    int i = 0;
    mutex = CreateSemaphore(NULL, 20, 20, NULL);
    empty = CreateSemaphore(NULL, 20, 20, NULL);
    full = CreateSemaphore(NULL, 0, 20, NULL);
    int totalThread = Producers+Consumers;
    buf.in = buf.out = 0;
    for(i = 0; i < Producers; i++)
    {
        hThread[i] = CreateThread(NULL,0,Consum,&i,0,&tid);
        if(hThread[i])
            WaitForSingleObject(hThread[i],10);
    }
    for(; i < totalThread; i++)
    {
        hThread[i] = CreateThread(NULL,0,Produce,&i,0,&tid);
        if(hThread[i])
            WaitForSingleObject(hThread[i],10);
    }
    return 0;
}
搜索更多相关主题的帖子: define NULL int Buffer out 
2018-04-07 10:12
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:507
帖 子:8890
专家分:53117
注 册:2011-1-18
得分:28 
将cout用临界区保护起来
2018-04-07 16:43
Queenlight
Rank: 1
等 级:新手上路
帖 子:18
专家分:0
注 册:2017-3-14
得分:0 
回复 2楼 rjsp
但是P、V操作不就是控制进入临界区的?
2018-04-08 17:15



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-485809-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.013868 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved