【问题标题】:How can simulate a join statement in a child thread that does not know who to join如何在不知道加入谁的子线程中模拟加入语句
【发布时间】:2014-07-17 20:59:23
【问题描述】:

我有三个线程:

  • 主要
  • thread1
  • 线程2

步骤:

  1. ma​​in 线程启动 thread1
  2. ma​​in 线程启动 thread2
  3. thread1 应该加入 thread2

如何在不使用加入/暂停和恢复的情况下执行此操作。

PS:thread1 不应该知道 thread2 的存在。

我使用suspend和resume来做这个,效果很好,但是我的老板不接受这个解决方案。

一段代码只是为了有个想法。这不是真正的代码。

public class Program
{
    static void Main(string[] args)
    {
        Thread thread1 = new Thread(() => Thread1Work());
        Thread thread2 = new Thread(() => Thread2Work());
        Thread thread3 = new Thread(() => StartWork(thread1, thread2));

        thread3.Start();

        if(CloseProgram())
        {
            thread2.Abort();
        }           
    }

    public static bool CloseProgram()
    {
        Stopwatch sw = new Stopwatch();
        while (true)
        {
            sw.Start();
            while (!EndProgram() && sw.ElapsedMilliseconds < 60000){ }

            if (sw.ElapsedMilliseconds > 60000)
            {
                sw.Stop();
                return false;
            }
            else
            {
                sw.Stop();
                return true;
            }
        }
    }

    public static void StartWork(Thread thread1, Thread thread2)
    {
        thread2.Start();

        thread1.Start();

        thread2.Suspend();

        while (thread2.IsAlive) { }

        thread1.Join();

        thread2.Resume();

        while (!thread2.IsAlive) { }

        thread2.Join();
    }

    public static void Thread2Work()
    {
        while(true){ DoSomething(); }
    }

    public static bool EndProgram()
    {
        if(someThing())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public static void Thread1Work()
    {
        DoOtherThing();
    }
}

【问题讨论】:

  • 如果第一个工作人员根本不知道,为什么还要等待第二个工作人员?显然,它在概念层面以某种方式依赖于它。此外,如果您这样做,则意味着这些线程正在执行另一个线程可观察到的副作用。这通常是个坏主意。尽量避免这样做。
  • 代码在上面,对不起,我昨天没时间发。

标签: c# multithreading join


【解决方案1】:

我假设您可以更改在两个线程上运行的代码。

您可以将信号量传递给线程 1 和 2,并让线程 1 调用 WaitOne,而线程 2 最后调用 Release。

【讨论】:

  • DoSomething() 方法不能更改,实际上我正在测试它的执行,thread2 必须开始运行,然后执行 thread1,thread1 删除了 thread2 需要完美工作的一些系统要求,并且线程应该没有完成它的工作,那就是测试。
【解决方案2】:

这很可能可以使用任务更好地处理。

将工作分解为离散的单元,等待前两个单元完成,然后使用 ContinueWith 方法有效地加入工作。

另外,生产者消费者模式可能更合适,在这种情况下,我建议查看 BlockingCollection 类来调解线程之间的通信。

但是,为了能够提供更详细的答案,问题中的更多细节将对您想要实现的目标有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    相关资源
    最近更新 更多