473,748 Members | 2,320 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

use of Queue

how is Queue intended to be used? I found the following code in python
manual, but I don't understand how to stop consumers after all items
have been produced. I tried different approaches but all of them
seemed incorrect (race, deadlock or duplicating queue functionality)
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()

q = Queue()
for i in range(num_worke r_threads):
t = Thread(target=w orker)
t.setDaemon(Tru e)
t.start()

for item in source():
q.put(item)

q.join() # block until all tasks are done
Aug 27 '08 #1
13 1848
Alexandru Mosoi wrote:
how is Queue intended to be used? I found the following code in python
manual, but I don't understand how to stop consumers after all items
have been produced. I tried different approaches but all of them
seemed incorrect (race, deadlock or duplicating queue functionality)
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()

q = Queue()
for i in range(num_worke r_threads):
t = Thread(target=w orker)
t.setDaemon(Tru e)
t.start()

for item in source():
q.put(item)

q.join() # block until all tasks are done
Put a sentinel into the queue that gets interpreted as "terminate" for the
workers. You need of course to put it in there once for each worker.

Diez
Aug 27 '08 #2
Alexandru Mosoi wrote:
how is Queue intended to be used? I found the following code in python
manual, but I don't understand how to stop consumers after all items
have been produced. I tried different approaches but all of them
seemed incorrect (race, deadlock or duplicating queue functionality)
def worker():
while True:
item = q.get()
if item is None:
break
do_work(item)
q.task_done()

q = Queue()
for i in range(num_worke r_threads):
t = Thread(target=w orker)
t.setDaemon(Tru e)
t.start()

for item in source():
q.put(item)
# stop all consumers
for i in range(num_worke r_threads):
q.put(None)
>
q.join() # block until all tasks are done
This is how I do it.

-- Gerhard

Aug 27 '08 #3

DiezPut a sentinel into the queue that gets interpreted as "terminate"
Diezfor the workers. You need of course to put it in there once for
Diezeach worker.

Or make the consumers daemon threads so that when the producers are finished
an all non-daemon threads exit, the consumers do as well.

Skip
Aug 27 '08 #4

skipOr make the consumers daemon threads so that when the producers
skipare finished an all non-daemon threads exit, the consumers do as
skipwell.

Forget that I wrote this. If they happen to be working on the token they've
consumed at the time the other threads exit, they will as well. Use the
sentinel token idea instead.

Skip
Aug 27 '08 #5
On Aug 27, 1:06*pm, Gerhard Häring <g...@ghaering. dewrote:
Alexandru Mosoi wrote:
how is Queue intended to be used? I found the following code in python
manual, but I don't understand how to stop consumers after all items
have been produced. I tried different approaches but all of them
seemed incorrect (race, deadlock or duplicating queue functionality)
* * def worker():
* * * * while True:
* * * * * * item = q.get()

* * * * * * * *if item is None:
* * * * * * * * * *break
* * * * * * do_work(item)
* * * * * * q.task_done()
* * q = Queue()
* * for i in range(num_worke r_threads):
* * * * *t = Thread(target=w orker)
* * * * *t.setDaemon(Tr ue)
* * * * *t.start()
* * for item in source():
* * * * q.put(item)

# stop all consumers
for i in range(num_worke r_threads):
* * *q.put(None)
* * q.join() * * * # block until all tasks are done

This is how I do it.

-- Gerhard

Your solution works assuming that you know how many consumer threads
you have :). I don't :). More than that, it's not correct if you have
more than one producer :). Having a sentinel was my very first idea,
but as you see... it's a race condition (there are cases in which not
all items are processed).
Aug 27 '08 #6
Your solution works assuming that you know how many consumer threads
you have :). I don't :). More than that, it's not correct if you have
more than one producer :). Having a sentinel was my very first idea,
but as you see... it's a race condition (there are cases in which not
all items are processed).
Queue raises an Empty exception when there are no items left in the
queue. Put the q.get() call in a try block and exit in the except
block.

You can also use a condition variable to signal threads to terminate.
Aug 27 '08 #7
On Aug 27, 2:54*pm, Jeff <jeffo...@gmail .comwrote:
Queue raises an Empty exception when there are no items left in the
queue. *Put the q.get() call in a try block and exit in the except
block.
Wrong. What if producer takes a long time to produce an item?
Consumers
will find the queue empty and exit instead of waiting.
You can also use a condition variable to signal threads to terminate.
This is the solution I want to avoid because it duplicates Queue's
functionality.
I prefer having a clean solution with nice design to hacking Queue
class.
Aug 27 '08 #8
On Aug 27, 12:45*pm, Alexandru Mosoi <brtz...@gmail. comwrote:
how is Queue intended to be used? I found the following code in python
manual, but I don't understand how to stop consumers after all items
have been produced. I tried different approaches but all of them
seemed incorrect (race, deadlock or duplicating queue functionality)

* * def worker():
* * * * while True:
* * * * * * item = q.get()
* * * * * * do_work(item)
* * * * * * q.task_done()

* * q = Queue()
* * for i in range(num_worke r_threads):
* * * * *t = Thread(target=w orker)
* * * * *t.setDaemon(Tr ue)
* * * * *t.start()

* * for item in source():
* * * * q.put(item)

* * q.join() * * * # block until all tasks are done

ok. I think I figured it out :). let me know what you think

global num_tasks, num_done, queue
num_tasks = 0
num_done = 0
queue = Queue()

# producer
num_tasks += 1
for i in items:
num_tasks += 1
queue.put(i)

num_tasks -= 1
if num_tasks == num_done:
queue.put(None)

# consumer
while True:
i = queue.get()
if i is None:
queue.put(None)
break

# do stuff

num_done += 1
if num_done == num_tasks:
queue.put(None)
break

Aug 27 '08 #9
>
Your solution works assuming that you know how many consumer threads
you have :). I don't :). More than that, it's not correct if you have
more than one producer :). Having a sentinel was my very first idea,
but as you see... it's a race condition (there are cases in which not
all items are processed).
If you have several producers, how do you coordinate when to shut down?

Apart from that, you can easily solve the problem of not knowing how many
consumers you have by making a consumer stuff back the sentinel into the
queue. Then it will ripple down until no consumer is left.

Diez
Aug 27 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
2785
by: phil | last post by:
And sorry I got ticked, frustrating week >And I could help more, being fairly experienced with >threading issues and race conditions and such, but >as I tried to indicate in the first place, you've >provided next to no useful (IMHO) information to >let anyone help you more than this This is about 5% of the code. Uses no locks.
9
2499
by: Brian Henry | last post by:
If i inherite a queue class into my class, and do an override of the enqueue member, how would i then go about actually doing an enqueue of an item? I am a little confused on this one... does over ride just add aditional code ontop of the current class or completely over ride it in vb? I am use to C++ this is the first inherited thing I've done in VB.NET... I'm a little unsure of diffrences, could someone explain this to me some? thanks!
4
2146
by: alisaee | last post by:
plz check what i have made wrong what is requierd her is to creat class queue and class stack and run the push,pop operation . #include<iostream.h> #include<conio.h> #include<stdio.h> class stack { public:
3
5152
by: Kceiw | last post by:
Dear all, When I use #include "queue.h", I can't link it. The error message follows: Linking... G:\Projects\Datastructure\Queue\Debug\main.o(.text+0x136): In function `main': G:\Projects\Datastructure\Queue\main.cpp:16: undefined reference to `Queue<char>::Queue()' G:\Projects\Datastructure\Queue\Debug\main.o(.text+0x394): In function `Z10do_commandcR5QueueIcE':
5
3111
Rooro
by: Rooro | last post by:
Hello everyone i'm working on : " Familiar childhood games such as hide and Go Seek and Tag involve determining the player who is to be "It". One method has the players stand in a circle while one of the players recites some rhyme to count off players, eliminating every nth player, where n depends on the number of the syllables in the counting rhyme. This process stops when only one player, the one to be "It" remains. This process...
2
2960
by: lavender | last post by:
When define a maxQueue is 10, means it able to store 10 items in circular queue,but when I key in the 10 items, it show "Queue Full" in items number 10. Where is the wrong in my code? Why it cannot store up to 10 items? Output from my code: Enter you choice: 1 Enter ID document to print : 21 Enter you choice: 1 Enter ID document to print : 22
3
2039
by: jrpfinch | last post by:
I have a script which is based on the following code. Unfortunately, it only works on Python 2.3 and not 2.5 because there is no esema or fsema attribute in the 2.5 Queue. I am hunting through the Queue.py code now to try to figure out how to make it work in 2.5, but as I am a beginner, I am having difficulty and would appreciate your help. Many thanks Jon
4
4598
by: j_depp_99 | last post by:
Thanks to those guys who helped me out yesterday. I have one more problem; my print function for the queue program doesnt work and goes into an endless loop. Also I am unable to calculate the length of my queue. I started getting compilation errors when I included a length function. <code> template<class ItemType> void Queue<ItemType>::MakeEmpty() {
2
2930
by: ecestd | last post by:
how do you implement a copy constructor for this pointer-based ADT queue #include <cassert // for assert #include <new // for bad_alloc using namespace std; //private:{Queue::Queue(const Queue& Q)}
0
2738
by: ecestd | last post by:
I did implement the copy constructor but still have a problem with it. It is not working. What could be wrong? #include "QueueP.h" #include <cassert // for assert #include <new // for bad_alloc #include <iostream> //typedef std::queue<QueueItemTypeQueue; using namespace std; //private:{Queue::Queue(const Queue& Q)}
0
8983
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8822
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9236
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8235
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6792
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6072
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4863
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2774
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2206
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.