I want to have two threads with a queue exchanging data (in the form of lists) between the two threads. However, at the moment I cannot fathom out how to write the code simply for taking the first list from the queue, processing it(which I have written the function for) and putting the returned data into a different queue. Can anyone give me any hints please?

I don't really understand the thread and queue modules in python, so am a bit stuck.

Recommended Answers

All 3 Replies

It's pretty easy:

from threading import Thread
from Queue import Queue

# first create the 2 queues you need
quxxx = Queue(10)
quyyy = Queue(10)

# then write the functions that the 2 threads will execute.
# in the functions, put and get items from the queues as you like.
# don't forget to call queue.task_done() after each queue.get()
def funcA():
    pass

def funcB():
    pass

# then create the 2 threads
thA = Thread(target=funcA)
thB = Thread(target=funcB)

# then start the threads
thA.start()
thB.start()

# then wait for the threads completion
thA.join()
thB.join()

# the end

It's pretty easy:

from threading import Thread
from Queue import Queue

# first create the 2 queues you need
quxxx = Queue(10)
quyyy = Queue(10)

# then write the functions that the 2 threads will execute.
# in the functions, put and get items from the queues as you like.
# don't forget to call queue.task_done() after each queue.get()
def funcA():
    pass

def funcB():
    pass

# then create the 2 threads
thA = Thread(target=funcA)
thB = Thread(target=funcB)

# then start the threads
thA.start()
thB.start()

# then wait for the threads completion
thA.join()
thB.join()

# the end

Many thanks for this it is a real help.
However, if I simply wanted to start only one thread that was seperate from the main thread, and use the two queues to pass data between the main thread and the other thread could I just use the start_new_thread function?

Many thanks for this it is a real help.
However, if I simply wanted to start only one thread that was seperate from the main thread, and use the two queues to pass data between the main thread and the other thread could I just use the start_new_thread function?

If you want to start a single thread, write the same code without funcB() and thB. The main thread can interact with thA through queues between thA.start() and thA.join().
It's not a good idea to use directly the methods of the thread module, like start_new_thread(). As the documentation says, this module contains low level functions. Use the module threading instead. Errors in thread programming may be difficult to track, and the module threading is safer.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.