我正在阅读提示和技巧帖子,我想我会尝试一些我以前从未做过的 C# 东西。因此,下面的代码没有实际用途,只是一个“测试功能”,看看会发生什么。
无论如何,我有两个静态私有字段:
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() 后立即运行;但相反,内部操作系统控件将按照它认为合适的方式启动线程。
编辑:不,他们不是,实际上,我只是认为他们是因为我的大脑错过了连续的数字
所以,我的问题是:导致我在输出的前“一半”中丢失几行的问题是什么?例如,' thread 3 setting threadInt to 84 '这一行在哪里?