我有一个脚本,用于将我的Twilio帐户的录音转移到S3。网络请求需要很长时间,所以我想我会使用线程并行运行多个请求。我的非线程代码的简化版本如下所示:
require 'twilio-ruby'
account_sid = 'sid'
auth_token = 'secret'
twilio_rest_client = Twilio::REST::Client.new(account_sid, auth_token)
recordings = twilio_rest_client.account.recordings.list(page_size: 2)
recordings.map do |recording|
recording.mp3! do |file|
path = recording.mp3.gsub('https://api.twilio.com/', '')
puts path
# add code to transfer to S3 here
end
end
这很好用。当我添加这样的线程时:
recordings.map do |recording|
Thread.new do
recording.mp3! do |file|
path = recording.mp3.gsub('https://api.twilio.com/', '')
puts path
# add code to transfer to S3 here
end
end
end.each(&:join)
有时它有效,有时我每次运行时都会遇到不同的错误,比如
/Users/michael/.rubies/ruby-2.2.5/lib/ruby/2.2.0/net/http.rb:1452:in `begin_transport': undefined method `closed?' for nil:NilClass (NoMethodError)
或
/Users/michael/.rubies/ruby-2.2.5/lib/ruby/2.2.0/net/protocol.rb:212:in `write0': undefined method `+' for nil:NilClass (NoMethodError)
或
/Users/michael/.rubies/ruby-2.2.5/lib/ruby/2.2.0/net/http.rb:923: [BUG] Segmentation fault at 0x00000000000000
我之前从未使用过它们,所以我没有正确使用线程吗?或者这只是twilio-ruby
库不是线程安全的指示器吗?