Ruby thread 新手,出了点问题。你能帮我找出问题所在吗?

标签 ruby multithreading

在线程中,我正在执行以下操作:

builder_thread = Thread.new do
    FileUtils.cp_r(folder,dest)
    io_object = IO.popen(command)
    Thread.current["output"] = ""
    Thread.current["pid"] = io_object.pid
    Thread.current["basedir"] = dest
    io_object.each { |out| Thread.current["output"] += out }
end

这工作正常,当我像 thread_var["output"] 一样访问线程的输出时。但是,如果我将代码变成这样:

builder_thread = Thread.new do
    dest = File.join(root_dir,"mydir")
    FileUtils.cp_r(folder,dest)
    io_object = IO.popen(command)
    Thread.current["output"] = ""
    Thread.current["pid"] = io_object.pid
    Thread.current["basedir"] = dest
    io_object.each { |out| Thread.current["output"] += out }
end

当我尝试访问 thread_var["output"] 时,它是 nil,就像下面的代码 io_object = IO.popen(command) 没有被执行一样.在第一种情况下,我在它到达线程之前创建了 dest 文件夹。第二,我在线程中创建它。你能帮我找出问题所在吗?

编辑:在该线程内执行的命令可能需要很长时间才能完成。同时,我希望能够访问 thread_var["output"] 变量并查看命令的执行情况。如果我在访问值之前加入线程,一切正常。但是,加入线程可能需要很长时间,我不想那样做。有解决办法吗?

最佳答案

可能会引发异常。主线程以外的线程中的异常不会打印到控制台 - 它们只会导致线程停止运行。

关于Ruby thread 新手,出了点问题。你能帮我找出问题所在吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2350930/

相关文章:

ruby 的 <=> 运算符和排序方法

javascript - 杂散开始标签 html 和 head

c++ - 我的等待 - 使用 std::mutex 的通知机制是否正确?

multithreading - SMP 并行的内存管理瓶颈

ruby-on-rails - ruby rails : check the amount of products a shop owns

ruby - Ruby 中的数字运算(需要优化)

ruby-on-rails - 如果我写 “:”冒号字符,则轮胎 Elasticsearch 错误

multithreading - 缺少的 “Comparison of Parallel Processing API”。如何选择多线程库?

string - 我如何在 Rust (crossbeam) 中与多个生产者和一个接收者共享字符串消息?

C# 在任务中更新 UI