如何避免在此代码中连续实例化Ruby Thread对象?(How to avoid consecutive instantiation of Ruby Thread object in this co

编程入门 行业动态 更新时间:2024-10-26 20:22:40
如何避免在此代码中连续实例化Ruby Thread对象?(How to avoid consecutive instantiation of Ruby Thread object in this code?)

我从未使用Thread直到现在,但我认为在这种情况下我必须依赖它。 我想分别处理一个cURL命令行的stdout和stderr,因为我想将进度指示器(写入stderr)中的回车符交换到换行符:

require "open3" cmd="curl -b cookie.txt #{url} -L -o -" Open3.popen3(cmd) do |stdin, stdout, stderr, wait_thr| pid = wait_thr.pid # I have to process stdout and stderr at the same time but #asyncronously, because stdout gives much more data then the stderr #stream. I instantiate a Thread object for reading the stderr, otherwise #"getc" would block the stdout processing loop. c=nil line="" stdout.each_char do |b| STDOUT.print b if c==nil then c="" thr = Thread.new { c=stderr.getc if c=="\r" || c=="\n" then STDERR.puts line line="" else line<<c end c=nil } end #if stderr still holds some output then I process it: line="" stderr.each_char do |c| if c=="\r" || c=="\n" then STDERR.puts line line="" else line<<c end end exit_status = wait_thr.value.exitstatus STDERR.puts exit_status end #popen3

我的问题是,在处理stdout(stdout.each_char)时,如何避免在每个循环周期中创建一个新的Thread实例? 我认为这很耗时,我想实例化一次,然后使用其停止和运行等方法。

I never used Thread till now, but I think I must rely on it in this case. I would like to process the stdout and the stderr of a cURL command line separately, because I want to exchange the carriage returns in the progress indicator (which is written to stderr) to newlines:

require "open3" cmd="curl -b cookie.txt #{url} -L -o -" Open3.popen3(cmd) do |stdin, stdout, stderr, wait_thr| pid = wait_thr.pid # I have to process stdout and stderr at the same time but #asyncronously, because stdout gives much more data then the stderr #stream. I instantiate a Thread object for reading the stderr, otherwise #"getc" would block the stdout processing loop. c=nil line="" stdout.each_char do |b| STDOUT.print b if c==nil then c="" thr = Thread.new { c=stderr.getc if c=="\r" || c=="\n" then STDERR.puts line line="" else line<<c end c=nil } end #if stderr still holds some output then I process it: line="" stderr.each_char do |c| if c=="\r" || c=="\n" then STDERR.puts line line="" else line<<c end end exit_status = wait_thr.value.exitstatus STDERR.puts exit_status end #popen3

My question is how can I avoid making a new Thread instance at every loop cycle when processing stdout (stdout.each_char)? I think it is time consuming, I would like to instantiate once, and then use its methods like stop and run etc.

更多推荐

本文发布于:2023-08-06 05:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1445027.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在此   实例   对象   代码   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!