Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

How to get the value 'foo' which is returned from the thread as shown below?

from threading import Thread

def foo(bar):

    print 'hello {}'.format(bar)

    return 'foo'

thread = Thread(target=foo, args=('world!',))

thread.start()

ret = thread.join()

print ret

 Returns None in the above case.

1 Answer

0 votes
by (25.1k points)

You can do it by using a queue. I have included the code to create a simple queue wrapper over an existing list, which you can modify if you wish. You can also use some other queue library as well.

Here you do not need to change the code that you wrote just add a queue as i have and it should work.

from threading import Thread

class Queue:

    def __init__(self):

        self.queue = []

    def enqueue(self, data):

        self.queue.append(data)

    def dequeue(self, data):

        data = None

        try:

            data = self.queue.pop(0)

        catch IndexError as ex:

            pass

        return data

    def is_empty(self):

        return len(self.queue) == 0

def foo(bar):

    print 'hello {0}'.format(bar)

    return 'foo'

q = Queue()

t = Thread(target=lambda q, arg: q.enqueue(foo(arg)), args=(q, 'world!'))

t.start()

t.join()

result = que.get()

print(result)

If you wish to learn more about python you can watch this video:

For more information, kindly refer to our Python Certification course.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...