1

Hi

Any one know how I can get the following function to return a value - thanks.

import threading
import time

def stringFunction(value):
    str = "This is string no. " + value
    return str

thread1 = threading.Thread(stringFunction("one"))
thread1.join()
thread1.start()
while threading.activeCount()>1:
    time.sleep(1)
print thread1

Currently returns "<Thread(Thread, stopped)>"
Not "This is string no. one"

Many thanks

5
Contributors
9
Replies
52
Views
7 Years
Discussion Span
Last Post by sekmani
0

Strange - I was running the script in NetBeans 6.7 and it was returning

"<Thread(Thread, stopped)>"

I tryed it in Python shell and got an error

"AssertionError: group argument must be None for now"

I guess i will have to double check problems in Python Shell in future...

Any how does any one know how I can return a value whilst using multi-thread - thanks

Revised code

import threading
import time
def stringFunction(value):
    str = "This is string no. " + value
    return str
thread1 = threading.Thread(stringFunction("one"))
thread1.start()
thread1.join()
while threading.activeCount()>1:
    time.sleep(1)
print thread1
0

Short answer, you don't do this. Usually when you want to get values from a thread you pass it a queue, and have a your main thread get values from the same queue.

A couple other things: you're calling join(), which will block until the thread is finished making the while loop directly after it unnecessary, and don't use "str" as a variable name since it's already the name of a builtin function.

import threading
import Queue

def stringFunction(value, out_queue):
    my_str = "This is string no. " + value
    out_queue.put(my_str)

my_queue = Queue.Queue()
thread1 = threading.Thread(stringFunction("one", my_queue))
thread1.start()
thread1.join()

func_value = my_queue.get()
print func_value
0

The tread must also be created by

thread1 = threading.Thread(target = stringFunction, arg = ("one", my_queue))

and not threading.Thread(stringFunction("one", my_queue)).

0

Thank you very much for your time - that was very helpful - Thank you

1

@sekmani Hi, yes you can directly print my_queue.get(). Also it is a good habit to call my_queue.task_done() after each call to my_queue.get(), although in this simple example, it doesn't change anything. Note that thread1.join() doesn't need to be called before my_queue.get(). You can join the thread at the end of the program, or at any moment when you need to be sure that the thread is finished.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.