Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1067459
  • 博文数量: 186
  • 博客积分: 4939
  • 博客等级: 上校
  • 技术积分: 2075
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-08 17:15
文章分类

全部博文(186)

文章存档

2018年(1)

2017年(3)

2016年(11)

2015年(42)

2014年(21)

2013年(9)

2012年(18)

2011年(46)

2010年(35)

分类: 系统运维

2017-01-17 21:27:50

    很久不写了,发一个最近的ruby多线程例子,没有线程同步问题,比较简单。

  1. require 'json'
  2. require 'rest-client'
  3. require 'thread'
  4. $contenct=[]
  5. def get_metrics
  6. get_json($content).select do |item|
  7. if /^opentsdb/ =~ item
  8. item
  9. end
  10. end
  11. end
  12. def batch_request(thread_index, items, result)
  13. tmp = []
  14. items.each_with_index do |item, index|
  15. begin
  16. res = JSON.parse(RestClient.get "{item}")
  17. rescue
  18. retry
  19. end
  20. puts "thread-#{thread_index}: #{index}:#{item}:#{res.size != 0}"
  21. tmp << "#{item},#{res.size != 0}"
  22. end
  23. result << tmp
  24. end
  25. def main
  26. metrics = get_metrics
  27. puts '*' * 144
  28. puts metrics.size
  29. groups = metrics.each_slice(400).to_a
  30. thread_jobs = []
  31. results = []
  32. groups.each_with_index do |items, index|
  33. thread_jobs << Thread.new { batch_request(index, items, results) }
  34. end
  35. thread_jobs.each { |thread| thread.join }
  36. puts '#' * 144
  37. records = 0
  38. open('data.csv', 'w+') do |file|
  39. results.each do |items|
  40. records += items.size
  41. items.each do |item|
  42. file << item + "\n"
  43. end
  44. end
  45. puts records
  46. end
  47. puts 'done'
  48. end
  49. main


阅读(4136) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~