Return Value of threads

# -*- coding: UTF-8 -*-
def foo(bar, result, index):
    print 'hello {0}'.format(bar)
    result[index] = "foo"

from threading import Thread

threads = [None] * 10
results = [None] * 10

for i in range(len(threads)):
    threads[i] = Thread(target=foo, args=('world!', results, i))
    threads[i].start()

# do some other stuff

for i in range(len(threads)):
    threads[i].join()

print " ".join(results)  # what sound does a metasyntactic locomotive make?

Basic example:

# -*- coding: UTF-8 -*-


import time
import threading


def myfunc(i):
        time.sleep(5)
        print "finished sleeping from thread %d"%(i)


def main():
        for i in range(10):
                t = threading.Thread(target = myfunc , args=(i,))
                time.sleep(1)
                t.start()
                print t.name


if __name__ == '__main__':
        main()

arrow
arrow
    全站熱搜

    JerryCheng 發表在 痞客邦 留言(0) 人氣()