So first you need to set up a worker function: def do_stuff(q): All you need to know for now, though, is that they use a worker function to get stuff done, they run at the same time, and you can pull them all together when they’re done. Start with importing the right stuff: from Queue import Queue The function would take 30 seconds every time it ran, and it would run 20 times so it would take 10 minutes to get through just 20 items. But what if it was trying to do a big task, or a task that required a lot of waiting (like pulling data from APIs)? Assume for example that do_stuff() takes 30 second to run each time and it’s just waiting on stupid APIs to return something. Notice how do_stuff() is just whipping through the whole queue. In like the most complicated way possible to output 0-19. Here’s an example of a simple program that uses Queues: from Queue import Queue That’s why I’m even bothering to bring them up here. In fact, you just can’t use lists the way you can use queues in threading. The big important point about Queues is that they work really well with threading. So let’s just say in Queues, you have to call this. If I don’t call task_done() then I run into trouble in threading. That tells the queue that not only have I retrieved the information from the list, but I’ve finished with it. The second visual difference is the task_done() bit at the end. It’s pretty dumb but I’m sure it’s useful somehow. First we set a maximum size to the queue, where 0 means infinite. There are only a couple differences in how queues work visually. The above code creates a list, assigns it three values, then removes the first value in so the list now has only 2 values (which are 2 and 3). from Queue import QueueĪ queue is kind of like a list: my_list = Let’s start with Queuing in Python.īefore you do anything else, import Queue. It’s the bare-bones concepts of Queuing and Threading in Python. So here’s something for myself next time I need a refresher. It sometimes feels like people make code, processes and even documentation opaque on purpose. I’ve never been a fan of programmer-speak.
0 Comments
Leave a Reply. |