我正在阅读技巧和窍门帖子,想尝试一些以前从未做过的C#编程内容。因此,以下代码没有实际用途,只是一个“测试函数”,用于查看发生了什么。
无论如何,我有两个静态私有字段:
你可以看到,我正在测试 ThreadStaticAttribute 和 volatile 关键字。
无论如何,我有一个测试方法像这样:
我希望看到这个函数返回的输出如下所示:
然而,我得到的是这个:
第二个“半部分”的输出符合预期(我想这意味着ThreadStatic字段正在像我想的那样工作),但似乎一些初始输出已经从第一个“半部分”中被“跳过”。
此外,第一个“半部分”的线程是无序的,但我理解当你调用Start()时,线程不会立即运行;而是内部操作系统控制将根据需要启动线程。编辑:实际上不是这样,我只是以为它们是因为我的大脑错过了连续的数字。
所以,我的问题是:是什么出了问题导致我在输出的前半部分丢失了几行?例如,'线程3将threadInt设置为84'这一行在哪里?
无论如何,我有两个静态私有字段:
private static volatile string staticVolatileTestString = "";
[ThreadStatic]
private static int threadInt = 0;
你可以看到,我正在测试 ThreadStaticAttribute 和 volatile 关键字。
无论如何,我有一个测试方法像这样:
private static string TestThreadStatic() {
// Firstly I'm creating 10 threads (DEFAULT_TEST_SIZE is 10) and starting them all with an anonymous method
List<Thread> startedThreads = new List<Thread>();
for (int i = 0; i < DEFAULT_TEST_SIZE; ++i) {
Thread t = new Thread(delegate(object o) {
// The anon method sets a newValue for threadInt and prints the new value to the volatile test string, then waits between 1 and 10 seconds, then prints the value for threadInt to the volatile test string again to confirm that no other thread has changed it
int newVal = randomNumberGenerator.Next(10, 100);
staticVolatileTestString += Environment.NewLine + "\tthread " + ((int) o) + " setting threadInt to " + newVal;
threadInt = newVal;
Thread.Sleep(randomNumberGenerator.Next(1000, 10000));
staticVolatileTestString += Environment.NewLine + "\tthread " + ((int) o) + " finished: " + threadInt;
});
t.Start(i);
startedThreads.Add(t);
}
foreach (Thread th in startedThreads) th.Join();
return staticVolatileTestString;
}
我希望看到这个函数返回的输出如下所示:
thread 0 setting threadInt to 88
thread 1 setting threadInt to 97
thread 2 setting threadInt to 11
thread 3 setting threadInt to 84
thread 4 setting threadInt to 67
thread 5 setting threadInt to 46
thread 6 setting threadInt to 94
thread 7 setting threadInt to 60
thread 8 setting threadInt to 11
thread 9 setting threadInt to 81
thread 5 finished: 46
thread 2 finished: 11
thread 4 finished: 67
thread 3 finished: 84
thread 9 finished: 81
thread 6 finished: 94
thread 7 finished: 60
thread 1 finished: 97
thread 8 finished: 11
thread 0 finished: 88
然而,我得到的是这个:
thread 0 setting threadInt to 88
thread 4 setting threadInt to 67
thread 6 setting threadInt to 94
thread 7 setting threadInt to 60
thread 8 setting threadInt to 11
thread 9 setting threadInt to 81
thread 5 finished: 46
thread 2 finished: 11
thread 4 finished: 67
thread 3 finished: 84
thread 9 finished: 81
thread 6 finished: 94
thread 7 finished: 60
thread 1 finished: 97
thread 8 finished: 11
thread 0 finished: 88
第二个“半部分”的输出符合预期(我想这意味着ThreadStatic字段正在像我想的那样工作),但似乎一些初始输出已经从第一个“半部分”中被“跳过”。
此外,第一个“半部分”的线程是无序的,但我理解当你调用Start()时,线程不会立即运行;而是内部操作系统控制将根据需要启动线程。编辑:实际上不是这样,我只是以为它们是因为我的大脑错过了连续的数字。
所以,我的问题是:是什么出了问题导致我在输出的前半部分丢失了几行?例如,'线程3将threadInt设置为84'这一行在哪里?