1. 程式人生 > >Python多工(利用threading建立執行緒時傳入引數--args引數)

Python多工(利用threading建立執行緒時傳入引數--args引數)

  target  : 指定 這個執行緒去哪個函式裡面去執行程式碼

  args:     指定將來呼叫 函式的時候   傳遞什麼資料過去

                  args引數指定的一定是一個元組型別

import threading
import time
g_nums = [1,2]

def test1(temp):
    temp.append(33)
    print("-----in test1 temp=%s-----"% str(temp))

def test2(temp):
    print("-----in test2 temp=%s-----"% str(temp))

def main():

    t1 = threading.Thread(target=test1,args=(g_nums,))  # 加上要傳遞的引數,元組型別
    t2 = threading.Thread(target=test2, args=(g_nums,))  # args 元組型別

    t1.start()
    time.sleep(1)

    t2.start()
    time.sleep(1)

    print("-----in main temp=%s-----"% str(g_nums))

if __name__ == '__main__':
    main()

結果:

 -----in test1 temp=[1, 2, 33]-----
-----in test2 temp=[1, 2, 33]-----
-----in main temp=[1, 2, 33]-----