求一个生产者-消费者问题的完全代码或者思想

sh270718120 2012-04-22 04:12:53
本人新手 框架里不知道写什么
...全文
171 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
我就是大神 2012-04-22
  • 打赏
  • 举报
回复
就像火车只有一个厕所,很多小孩要上厕所,家长带着小孩要去,但是厕所一次只能上一个,大人还要做其他事,不能一直等着。然后就有列车员会将小孩收集起来,一个一个带着上厕所。家长就有时间干其他的了。
sh270718120 2012-04-22
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Produce_and_Consumer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
allgoods = new int[10];
}
Thread consumer;
Thread producer;
object store;
int sum = 2;
int goods = 0;
int[] allgoods;
int totaltimes = 5;//模拟操作的次数
int times1 = 0;
int times2 = 0;
int produce_speed = 1;
int consume_speed = 1;
delegate void dele();
private void consume()
{
while (times1 != totaltimes)
{
if (goods > 0)
{
lock (store)
{
Thread.Sleep(1000 * consume_speed);
consume_label.Text += string.Format("商品{0}\n", times1 + 1);
times1++;
goods--;
this.Refresh();
}
}
}
}
private void produce()
{
while (times2 != totaltimes)
{
if (goods < sum)
{
lock (store)
{
Thread.Sleep(1000 * produce_speed);
produce_label.Text += string.Format("商品{0}\n", times2 + 1);
times2++;
goods++;
this.Refresh();
//Interlocked.Increment(ref goods);
}
}
}
}

private void button1_Click(object sender, EventArgs e)
{
consumer = new Thread(invokeforconsumer);
producer = new Thread(invokeforproducer);
store = new object();
producer.Start();
consumer.Start();
}
private void invokeforconsumer()
{
dele forconsumer = new dele(consume);
this.BeginInvoke(forconsumer);
}
private void invokeforproducer()
{
dele forproducer = new dele(produce);
this.BeginInvoke(forproducer);
}

}
}
我写的这个有时候会出现调试时候卡死问题这是为什么
threenewbee 2012-04-22
  • 打赏
  • 举报
回复
关键就是对增加或者移除商品的过程做同步,不允许生产者消费者同时去访问。
机器人 2012-04-22
  • 打赏
  • 举报
回复
发布-订阅。简单就用 事件 或者 代理 实现了。
sh270718120 2012-04-22
  • 打赏
  • 举报
回复
在线等回复啊

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧