【发布时间】:2011-04-04 19:20:57
【问题描述】:
我正在做一个需要多线程同步的程序。这是我的方法:
private void RunSimulation()
{
int sideSize = (int)Math.Ceiling((double)_simulationField.GetLength(0) / (double)MAX_SECTOR_SIZE);
int threadsCount = sideSize * sideSize;
sync = new bool[threadsCount + 1];
for (int i = 0; i < sync.Length; i++)
{
sync[i] = false;
}
for (int sector = 0; sector <= threadsCount; sector++)
{
Thread sectorThread = new Thread(DoSector);
sectorThread.IsBackground = true;
sectorThread.Start(sector);
}
}
还有:
private void DoSector(object obj)
{
int sector = (int)obj;
Library.Pair sectorPosition = GetSectorPosition(sector);
while (true)
{
for (int i = sectorPosition.X; i < sectorPosition.X + MAX_SECTOR_SIZE && i < _simulationField.GetLength(0); i++)
{
for (int j = sectorPosition.Y; j < sectorPosition.Y + MAX_SECTOR_SIZE && j < _simulationField.GetLength(1); j++)
{
if (_simulationField[i, j] != null)
{
MoveCreature(_simulationField[i, j], i, j);
}
}
}
sync[sector] = true;
while (sync.Contains(false) && sector != sync.Length)
{
Thread.Sleep(10);
}
if (sector == sync.Length)
{
for (int i = 0; i < sync.Length; i++)
{
sync[i] = true;
}
}
Thread.Sleep(500);
}
}
所以你可以看到我正在使用一个数组进行同步。但我在徘徊是这样做的好方法吗?这里的 sync.Contains 操作复杂度为 O(n),并且处于循环中...有没有更好的同步方法?
【问题讨论】:
标签: c# multithreading synchronization