Threadlocal值iList排序

时间:2015-11-29 02:49:39

标签: c# thread-local

您好我有一个创建2个线程的示例。我的问题是,当我输出值时,它总是在999之前打印1000.是否可以在1000之前打印999.只是想知道它们是如何订购的?

/cli/aaa/bbb/ccc.php

1 个答案:

答案 0 :(得分:0)

通常,您不应该编写多线程代码,其中哪些线程首先取决于哪个完成。

但您的要求可以使用Semaphore / WaitHandle

来实现
//Creates semaphore with 1 possible owner and the owner slot taken
var sema = new Semaphore(1, 1);

Thread firstThread = new Thread(new ThreadStart(() =>
{
        //Value set and sema is released, if this thread calls release
        //before `secondThread` attempts to acquire then there will be no stalling
        field.Value = 999;
        sema.Release();
}));

Thread secondThread = new Thread(new ThreadStart(() =>
{
        sema.WaitOne();
        field.Value = 1000;
}));

阅读本书(信息量小书):第3章 - 基本同步模式,了解有关基本信令/等待的更多信息: http://www.greenteapress.com/semaphores/downey08semaphores.pdf