【发布时间】:2016-01-05 09:49:59
【问题描述】:
我想在 C# 中模拟生产者消费者。一个线程作为生产者工作,新的数组对象,并将该数组放入 List。另一个线程作为消费者,当 List 中有元素时,它获取数组并执行某物。代码在这里。为什么过程中有“空”。如何解决? 调用list.add(tmp)时引起的问题,list.Count在ushort [] tmp准备好之前加一。谁能解释这个过程的机制。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace listTest
{
class Program
{
static List<ushort[]> list = new List<ushort[]>();
static void func1()
{
while (true)
{
ushort[] tmp;
while (true)
{
tmp = new ushort[100];
if (tmp != null)
break;
}
list.Add(tmp);
Thread.Sleep(10);
}
}
static void func2()
{
while (true)
{
if (list.Count > 0)
{
ushort[] data = list.ElementAt(0);
if (data == null)
Console.Write("null\n");
else
{
for (int i = 0; i < data.Length; i++)
{
data[i] += 1;
}
}
Console.Write("ok ");
list.RemoveAt(0);
}
}
}
static void Main(string[] args)
{
Thread func1T = new Thread(func1);
Thread func2T = new Thread(func2);
func1T.Start();
func2T.Start();
}
}
}
【问题讨论】:
-
设置断点并通过代码进行调试。
-
hmm,2 个线程有一个非线程安全列表且没有锁,看来您必须先阅读有关多线程编程的知识。
-
@user1666620,这不太可能有帮助。调试多线程 bug 并非易事。
-
如何跳出 func1 @sounder 中的第一个 while 循环?
标签: c#