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

Recommended Answers

All 9 Replies

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

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

The tread must also be created by

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

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

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

Can't we do this without join() method ?

@Sagar_5 Can you explain what you want to do exactly ? You can perhaps start a new forum thread with your question.

@Gribouillis i can put directly print my_queue.get() ?? thanks :)

@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.

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.