How to make worker threads quit after work is finished in a multithreaded producer-consumer pattern?

后端 未结 4 1634
时光说笑
时光说笑 2021-02-05 12:56

I am trying to implement a multithreaded producer-consumer pattern using Queue.Queue in Python 2.7. I am trying to figure out how to make the consumers, i.e. the worker threads,

4条回答
  •  你的背包
    2021-02-05 13:32

    Just for completeness sake: You could also enqueue a stop signal which is -(thread count). Each thread then can increment it by one and re queue it only if the stop signal is != 0.

        if data < 0: # negative numbers are used to indicate that the worker should stop
            if data < -1:
                q.put(data + 1)
            # Commit suicide.
            print 'worker', n, 'is exiting'
            break
    

    But i'd personally go with Travis Mehlinger or Daniel Sanchez answer.

提交回复
热议问题