【问题标题】:Threadlocal values iList orderingThreadlocal 值 iList 排序
【发布时间】:2016-03-02 22:12:22
【问题描述】:

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

 static void Main(string[] args)
    {
        ThreadLocal<int> field = new ThreadLocal<int>(() => 0, true);



        Thread firstThread = new Thread(new ThreadStart(() =>
        {

            field.Value = 999;
        }));
        Thread secondThread = new Thread(new ThreadStart(() =>
        {

            field.Value = 1000;
        }));


        firstThread.Start();
        secondThread.Start();


        firstThread.Join();
        secondThread.Join();

        IList<int> valueList = field.Values;

        foreach (int arr in valueList)
            Console.WriteLine(arr);


        Console.Read();
    }

【问题讨论】:

  • 线程并行运行,不保证哪个先执行。

标签: c# thread-local


【解决方案1】:

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

但是您的要求可以通过 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;
}));

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

【讨论】:

    猜你喜欢
    • 2012-07-03
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多