【发布时间】:2013-04-16 22:34:59
【问题描述】:
我是编程的初学者,我想知道同步线程。
我有一个 WinForms 程序,它需要为每个 cpu 内核创建线程并运行一个方法指定的次数。
我在嵌套循环中设置和运行线程,但我的输出是这样的;
thread: 0, run: 1, time: xxx
thread: 1, run: 1, time: xxx
thread: 2, run: 1, time: xxx
thread: 3, run: 1, time: xxx
thread: 1, run: 2, time: xxx
thread: 2, run: 2, time: xxx
等等。但是我希望输出像这样显示数据:
thread: 0, run: 1, time: xxx
thread: 0, run: 2, time: xxx
thread: 0, run: 3, time: xxx
thread: 1, run: 1, time: xxx
thread: 1, run: 2, time: xxx
thread: 1, run: 3, time: xxx
等等
在我的表单中,我创建线程并从一个单独的类中调用一个方法,就像这样;
SomeClass[] thisArray = new SomeClass[numThreads];
for (int runNumber = 1; runNumber <= numberOfRuns; runNumber++)
{
for (int i = 0; i < numThreads; i++)
{
thisArray[i].mThread = new Thread(thisArray[i].StartMethod);
thisArray[i].mThread.Start();
thisArray[i].mThread.Join();
//Display thread id and number of runs
this.tBoxW.AppendText(string.Format("") + Environment.NewLine);
this.tBoxW.AppendText(string.Format("Thread Id: ") + i.ToString() +
Environment.NewLine);
this.tBoxW.AppendText(string.Format("Number of Runs {0}", numberOfRuns) +
Environment.NewLine);
}
}
SomeClass 位于 SomeClass.cs 中,并提供 StartMethod() 方法,该方法通过一系列方程运行。
为了以我想要的方式获得输出,我是否正确地假设我需要同步线程?或者也许有更简单的方法?
由于我刚开始使用线程,我正在寻找实现所需输出的最简单方法。
任何帮助将不胜感激。感谢您花时间查看我的问题。
【问题讨论】:
-
启动一个线程然后调用 Join() 是没有意义的。您不妨直接调用 StartMethod() 。仅在循环外加入 Join()。
-
谢谢汉斯,我会试试这个
-
@Hans Passant:是的,这基本上使他的解决方案连续
标签: c# multithreading synchronization