如何在给定点停止线程? [英] How to Stop a Thread at a given point?

查看:52
本文介绍了如何在给定点停止线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图停止一些线程,阅读一些关于优雅地完成它的正确方法的内容,但我一定是做错了什么,因为它根本不起作用.起初我尝试不使用 lock() 并且 _IsRunning 是易失性的,然后尝试使用锁.这是我所拥有的.

I was trying to stop some threads, read some things about the proper way to do it gracefully, but I must be doind something wrong because it simply doesn't work. At first I tried without the lock() with _IsRunning being volatile, then tried with the locks. Here is what I've got.

private volatile bool _IsRunning;
private static readonly object runLock = new object();

public void Start()
{
    if (_IsRunning == true)
        return;
    _IsRunning = true;
    (new System.Threading.Thread(new System.Threading.ThreadStart(SendLoop))).Start();
}

public void Stop()
{
    lock (runLock)
    {
        _IsRunning = false;
    }
}

private void SendLoop()
{
    while (_IsRunning)
    {
        lock (runLock)
        {
            if (_sockets.Count > 0)
            {
                //some stuff
            }
            else
            {
                System.Threading.Thread.Sleep(10);
            }
        }
    }
}

我在 while() 处设置了断点,即使我传入了 Stop()_IsRunnig 仍然为真.>

I set a breakpoint at my while(), and _IsRunnig is still true even though I passed in Stop().

推荐答案

这里需要锁,因为你的 start 方法的编写方式,但是你只需要 Start() 中的锁(现在不是)和 Stop(),因为它们是唯一可能在您的情况下导致竞争条件的.

The lock is required here because of the way your start method is written, however, you only need the lock in Start() (where it isn't now) and Stop(), since they're the only ones that could potentially cause a race condition in your case.

我会完全从您的 SendLoop() 方法中移除锁(这会导致 DeadLock 因为 Stop 正在等待锁设置 _isRunning,并且您的 SendLoop 一直持有锁直到 _isRunning 设置为 false).现在,当您调用 Stop() 时,锁会阻止它设置 _isRunning = false;

I would remove the lock from your SendLoop() method entirely (it's causing a DeadLock since Stop is waiting on the lock to set _isRunning, and your SendLoop is holding the lock until _isRunning is set to false). Right now, when you call Stop(), the lock is preventing it from ever setting _isRunning = false;

但是,您需要在 Start()Stop() 方法中加锁(除非您完全修改它们的结构).类似的东西:

However, you will need locks in your Start() and Stop() methods (unless you rework the way they are structured entirely). Something like:

public void Start()
{
    lock (runLock)
    {
        if (_IsRunning == true)
            return;
        _IsRunning = true;
        (new System.Threading.Thread(new System.Threading.ThreadStart(SendLoop))).Start();
    }
}

public void Stop()
{
    lock (runLock)
    {
        _IsRunning = false;
    }
}

这将保护您免于启动 2 个线程,并且还将防止 Stop 在线程启动之前停止.

This will protect you from starting 2 threads, and will also keep Stop from stopping before the thread has started.

这篇关于如何在给定点停止线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆