BLACK CAT PROGRAMMER

python thread – 2

Another python threading implementation

import threading
import random
import signal
import queue
import time

work_queue = queue.Queue()
is_running = True

def consumer():
  while is_running:
    task = work_queue.get()
    print("doing: {}".format(task))
    
def producer():
  while is_running:
    task = random.random()
    work_queue.put(task)
    time.sleep(10*random.random())

def shutdown():
  print("terminating...")
  is_running = False
  
def main():
  print("starting two threads")
  t1 = threading.Thread(target=consumer, name="consumer")
  t2 = threading.Thread(target=producer, name="producer")
  
  signal.signal(signal.SIGINT, shutdown)
  
  t1.start()
  t2.start()
  
  t1.join()
  t2.join()
  
  print("bye")

  
if __name__ == "__main__":
  main()

Previous implementation: http://hong.ddns.net/wp-admin/post.php?post=164&action=edit

Posted in notesTagged , ,

python threading

經常忘記 python threading 的用做法,今次寫一個簡單的起手式,方便日後ref

import os
import threading
import time
import queue
import random


class Consumer(threading.Thread):
  def __init__(self, queue, name="consumer"):
    threading.Thread.__init__(self);
    self.name = name
    self.running = True
    self.queue = queue
    self.doneTaskCount = 0
    self.hp = 10

  def run(self):
    while self.running:
      task = self.queue.get();
      time.sleep(2)
      self.doneTaskCount += 1
      print("{} done task (#{}): {}".format(self.name, self.doneTaskCount, task))
      self.hp -= 1
      if self.hp <= 0:
        self.running = False

class Producer(threading.Thread):
  def __init__(self, queue, name="producer"):
    threading.Thread.__init__(self);
    self.name = name
    self.running = True
    self.queue = queue
    self.hp = 10
    self.doneTaskCount = 0

  def run(self):
    while self.running:
      time.sleep(1)
      task = random.random() * 100
      self.queue.put(task)
      self.doneTaskCount += 1
      print("{} created task (#{}): {}".format(self.name, self.doneTaskCount, task))
      
      self.hp -= 1
      if self.hp <= 0:
        self.running = False
          
# main
def main():
  print("start main")
  Q = queue.Queue()
  producer = Producer(Q, "Producer 1")
  consumer = Consumer(Q, "Consumer 1")
  
  producer.start()
  consumer.start()
  
  print(threading.current_thread())
  
  producer.join()
  consumer.join()
  print("performing cleaning, supposed after all thread finished")
  

if __name__ == "__main__":
  main()
Posted in notesTagged , ,