【问题标题】:python multithreading application for fetching messages from rabbitmq用于从rabbitmq获取消息的python多线程应用程序
【发布时间】:2018-11-26 10:15:02
【问题描述】:

Worker.counter =0 confobj.thread_count =2

def callback(ch, method, properties, body):
    if(Worker.counter<confobj.thread_count):
      logObject = json.loads(body)
      th=Worker(Worker.counter+1,logObject,confobj,fileobj)
      Worker.counter+=1
      th.start()
    else:
      print("All threads are busy.") 
      time.sleep(2)  
    ch.basic_ack(delivery_tag = method.delivery_tag)

  channel.basic_qos(prefetch_count=1)
  channel.basic_consume(callback,
                        queu`enter code here`e=confobj.queue)
  channel.start_consuming()

我希望 maxthread 应该是 2 以便第一个线程访问第一条消息,第二个线程访问第二条消息,第一个线程再次访问第三条消息,依此类推 然后我想将该消息插入弹性搜索而不跳过任何消息。

【问题讨论】:

  • 请发布解决此问题的尝试(代码)

标签: python-3.x multithreading rabbitmq


【解决方案1】:

您可以尝试使用来自 Multiprocessing 的 Process 并调用 Process.pid 函数来获取对每个进程 ID 的访问权限。

【讨论】:

  • 我想要整个 python 程序
【解决方案2】:
from multiprocessing import Process, current_process


def square(x):
print(x*x)
print('processID =', current_process())
return x * x


def cube(y):
print(y*y*y)
print('processID =', current_process())
return y * y * y


if __name__ == '__main__':
number = 6
one = Process(target=square, args=(number,))
two = Process(target=cube, args=(number,))

one.start()
two.start()

one.join()
two.join()

这里是一个简单的例子,使用具有不同功能的 Process。因此,您可以通过进程 ID 调用 .start()。 (这不是一个复杂的代码。这只是一个理解的例子)。

【讨论】:

  • 我想用两个线程访问4条消息,我该怎么办?
  • 这到底是什么意思?据我了解,您需要一种具有 3 个线程或进程的 cicle,它们对已处理列表的每三个元素使用单独的线程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
  • 1970-01-01
  • 2017-01-19
  • 2015-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多