开发者

Ruby thread newbie,something went very wrong.Can you help me spot what it is?

In a thread, I'm doing the following:

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

and this works ok, when I access the thread's output like thread_var["output"]. However, if I turn the code into this:

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

when I try to access thread_var["output"] is nil, just like if the code below io_object = IO.popen(command) doesn't get executed. In the first case, I'm creating the dest folder before it gets to the thread. In the second, I'm creating it in the thread. Can you help me figure out what's wrong?

EDIT: The command that gets executed inside that thread may take a very long time to complete. Meanwhile, I'd like to be able to access the thread_var["out开发者_StackOverflow中文版put"] variable & see how the command is doing. If I join the thread right before I access the value, everything works ok. However, joining the thread may take a very long time, and I like to not do that. Is there a way around this?


It's possible that an exception is being raised. Exceptions in threads other than the main thread aren't printed to the console - they just cause the thread to stop running.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜