从外部停止线程 [英] Stop a thread from outside

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

问题描述

我有一个线程在后台执行操作,并且我想在我的程序有实际操作时暂停它.一旦完成,我希望后台线程继续.例如

I have a thread doing things in background and I want to suspend it whenever my program has a real thing to do. Once that is finished I want the background thread to continue. E.g.

ta = Thread.new { loop { print 'a'; sleep 0.2 } }

sleep 0.5

# put ta to sleep
5.times { print 'b'; sleep 0.2 }
# let ta resume

sleep 0.8
puts

输出应该类似于aaabbbbbaaaaa.目前它是aaabababababaaaaa.

The output should be something like aaabbbbbaaaaa. Currently it is aaabababababaaaaa.

虽然线程可以通过 Thread.stop 停止自身,但我没有找到从外部"停止线程的方法.有没有简单的解决办法?

Although a thread can stop itself through Thread.stop, I found no method to stop a thread from "outside". Is there a simple solution?

推荐答案

你需要的是一个 Mutex:

$my_mutex = Mutex.new

t1 = Thread.new do
  loop do
    $my_mutex.synchronize do
      print 'a'
    end
    sleep 0.2
  end
end

sleep 0.5

$my_mutex.synchronize do
  5.times do
    print 'b'
    sleep 0.2
  end
end

sleep 0.8

puts
sleep

输出:

aaabbbbbaaaaa
aaaaaaaaaaaaaaaaa...

这篇关于从外部停止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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