【发布时间】:2016-06-28 08:51:36
【问题描述】:
Abraham Silberschatz-Operating System Concepts 一书中使用 c# 的生产者消费者问题。 我已经用 C# 编写了这个伪代码的代码,但是出现了一个警告“在第 43 行检测到无法访问的代码”......我是编程新手..需要一点指南来解决这个问题!
书中给出的伪代码:
#define BUFFER_SIZE 5
typedef struct {
. . .
} item;
item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
制作人:
item next_produced;
while (true) {
/* produce an item in next produced */
while (((in + 1) % BUFFER_SIZE) == out)
; /* do nothing */
buffer[in] = next_produced;
in = (in + 1) % BUFFER_SIZE;
}
消费者:
item next_consumed;
while (true) { while (in == out)
; /* do nothing */ next_consumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
/* consume the item in next consumed */
}
我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace producer_consumer_problem_Csharp
{
struct item
{
private int iData;
public item(int x)
{
this.iData = x;
}
};
class Program
{
static void Main(string[] args)
{
int Buffer_Size = 5;
item[] buffer = new item[Buffer_Size];
int inp = 0;
int outp = 0;
item next_produced;
while(true)
{
Console.WriteLine("Enter the next produced item");
int x = Convert.ToInt32( Console.ReadLine() );
next_produced = new item(x);
while ((inp + 1) % Buffer_Size == outp) ;
// do nothing
buffer[inp] = next_produced;
inp = (inp + 1) % Buffer_Size;
}
item next_consumed = new item();
while (true)
{
while (inp == outp);
/*donothing*/
next_consumed = buffer[outp];
outp = (outp +1) % Buffer_Size; /* consume the item in next consumed */
Console.WriteLine("Next consuumed item is: {0} ", next_consumed);
}
}
}
}
【问题讨论】:
-
您的第二个
while循环永远不会到达,因为您的第一个循环是无限循环,如while(true)。 -
那是不是说明书中给出的伪代码是错误的! ......我已经从这个伪代码实现了代码......那里给出了无限循环。
-
不,这本书没有说谎。生产者和消费者应该在并发线程中运行。
标签: c# c#-4.0 operating-system c#-3.0 c#-2.0