Multithreading in Python

The package for multithreading

The package threading is for multithreaded programming in python. To get it ready to use, one should import it. As:

import threading

Get your hand dirty

import threading

def add(n):
    print('I am working.')
    result = n + 1000
    return result

thread0 = threading.Thread(target=add, args=(1,))
thread0.start()

This code could be able to run. There is a function add(n) defined. Then, a thread was created to run the function. The argument, target, tells the thread which function is going to be run. The argument, args, tells the thread what is the arguments fed the target function.
NOTE: The fed value for args of the thread must be a tuple. So, if you’re going to feed the function just one value, the comma is also needed.

How to get the value returned

import threading

class MyThread(threading.Thread):

    def __init__(self,func,args=()):
        super(MyThread,self).__init__()
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        try:
            return self.result  # 如果子线程不使用join方法,此处可能会报没有self.result的错误
        except Exception:
            return None

def add(n):
    print('I am working.')
    result = n + 1000
    return result
################
thrdList = []
for i in range(4):
    t = MyThread(add, args=(i,))
    thrdList.append(t)
    t.start()

reslutList = []
for t in thrdList:
    t.join()
    reslutList.append(t.get_result())

print(reslutList)

output:
这里写图片描述
t.join(): It could be interpreted as wait_until_finished(t). Whitout this sentence, the thread may just have done half of its job, the main thread read its result. In this scenario, the main thread read a wrong result.

REF:
multithreading - what is the use of join() in python threading - Stack Overflow
https://stackoverflow.com/questions/15085348/what-is-the-use-of-join-in-python-threading
python multithreading wait till all threads finished - Stack Overflow
https://stackoverflow.com/questions/11968689/python-multithreading-wait-till-all-threads-finished
python - Use of threading.Thread.join() - Stack Overflow
https://stackoverflow.com/questions/19138219/use-of-threading-thread-join

Reference:

python获取多线程的返回值 - Hu知非 - 博客园
https://www.cnblogs.com/hujq1029/p/7219163.html?utm_source=itdadao&utm_medium=referral
multithreading - what is the use of join() in python threading - Stack Overflow
https://stackoverflow.com/questions/15085348/what-is-the-use-of-join-in-python-threading
python multithreading wait till all threads finished - Stack Overflow
https://stackoverflow.com/questions/11968689/python-multithreading-wait-till-all-threads-finished
python - Use of threading.Thread.join() - Stack Overflow
https://stackoverflow.com/questions/19138219/use-of-threading-thread-join

posted on 2017-11-20 14:20  yusisc  阅读(20)  评论(0编辑  收藏  举报

导航