Python多執行緒threading的使用

2022-08-05 12:12:14 字數 2559 閱讀 1597

一. threading的引數傳遞,引數之後的’,‘不能少,此處的’,‘是用來區分此引數作為元組(包含多個引數)來傳遞的,而不是單個引數傳遞

#coding:utf-8

import threading

import time

def b(arg):

time.sleep(2)

print(

"i'm b")

print(

"i'm

", threading.current_thread().name)

print(

"i'm

",arg)

time.sleep(2)

print(

"i'm sleep after")

def a():

print(

"i'm a")

s = threading.thread(target=b, name='

loopthread

',args=("test"

,)) s.start()

print(

"i'm

",threading.current_thread().name)

#time.sleep(3)

print(

"i'm c")

print(a())

二. sleep的位置很重要,如上輸出結果:

i'm a

i'm mainthread

i'm c

none

i'm b

i'm loopthread

i'm test

i'm sleep after

第二種情況:

#coding:utf-8

import threading

import time

def b(arg):

#time.sleep(2)

print(

"i'm b")

print(

"i'm

", threading.current_thread().name)

print(

"i'm

",arg)

time.sleep(2)

print(

"i'm sleep after")

def a():

print(

"i'm a")

s = threading.thread(target=b, name='

loopthread

',args=("

test

",))

s.start()

print(

"i'm

",threading.current_thread().name)

#time.sleep(3)

print(

"i'm c")

print(a())

輸出結果:

i'm a

i'm bi'm

i'm loopthread

i'm test

mainthread

i'm c

none

i'm sleep after

第三種情況:

#coding:utf-8

import threading

import time

def b(arg):

#time.sleep(2)

print(

"i'm b")

print(

"i'm

", threading.current_thread().name)

print(

"i'm

",arg)

time.sleep(2)

print(

"i'm sleep after")

def a():

print(

"i'm a")

s = threading.thread(target=b, name='

loopthread

',args=("

test

",))

s.start()

print(

"i'm

",threading.current_thread().name)

time.sleep(3)

print(

"i'm c")

print(a())

輸出結果:

i'm a

i'm bi'm

mainthread

i'm loopthread

i'm test

i'm sleep after

i'm c

none

似乎其中一個執行緒稍微阻塞(或睡眠)就會立馬開始執行另外一個,可以據此調控兩個執行緒的交替?

關於執行緒的引數傳遞需要注意

python之多執行緒threading模組的使用

import threading print threading active count 返回當前存活的執行緒數量 輸出1 print threading enumerate 返回當前所有存活的執行緒列表 輸出 mainthread started print threading current th...

python threading關於鎖的內容

鎖 import threading time defaddnum global num lock acquire 獲取鎖 temp num...

python中threading模組中的Join類

join類是threading中用於堵塞當前主執行緒的類,其作用是阻止全部的執行緒繼續執行,直到被呼叫的執行緒執行完畢或者超時。具體 如下 import threading time defdowaiting print start waiting time strftime s time sleep 3...