python中線程

2021-08-22 02:24:49 字數 1404 閱讀 1925

程序和執行緒的區別:

1.程序:每個程式都會有乙個程序,負責管理程式各個功能的執行,程序只會有乙個

而且至少有乙個(相當於包工頭)

2.執行緒:每個程序裡面至少有乙個執行緒,稱之為主線程,除此以外還會有其他執行緒,稱之為分執行緒

執行緒是控制任務執行的最小單位(相當於農名工)

3.程序負責控制各個執行緒的執行,當程式執行,程序啟動,程式關閉,程序結束

主線程和分執行緒:

1.**執行預設都是在主線程裡面,如果需要執行新的任務,可以開闢分執行緒

2.分執行緒個數沒有限制,分執行緒裡面的任務結束後,分執行緒結束

分執行緒的使用場景:

1.當有大量任務需要執行的時候,可以將任務放入到分執行緒裡面

2.當有大量任務需要執行的時候,而任務的執行順序需要指定的時候,可以使用分執行緒

3.當介面有大量介面需要更新的時候,需要放入到分執行緒

下面有一段**表示:

import  threading

import time

exitflag = 0

class mythread(threading.thread): # 繼承父類threading.thread

def __init__(self, threadid, name, counter):

threading.thread.__init__(self)

self.threadid = threadid

self.name = name

self.counter = counter

def run(self): # 把要執行的**寫到run函式裡面 執行緒在建立後會直接執行run函式

print("starting " + self.name)

print_time(self.name, self.counter, 5)

print("exiting " + self.name)

def print_time(threadname, delay, counter):

while counter:

if exitflag:

(threading.thread).exit()

time.sleep(delay)

print("%s: %s" % (threadname, time.ctime(time.time())))

counter -= 1

# 建立新執行緒

thread1 = mythread(1, "thread-1", 1)

thread2 = mythread(2, "thread-2", 2)

# 開啟執行緒

thread1.start()

thread2.start()

print("exiting main thread")

python 中線程

import threading import time class test threading.thread 繼承threading.thread def init self super test,self init def run self 設定執行緒方法 threadname threadi...

python中線程程式設計

一 執行緒 執行緒也是實現多工的一種方式,乙個程序中,也經常需要同時做多件事,就需要同時執行多個 子任務 這些子任務就是執行緒。乙個程序可以擁有多個並行的執行緒,其中每乙個執行緒,共享當前程序的資源。在python程式中,可以通過 thread 和threading 推薦使用 這兩個模組來處理執行緒...

Python中線程的使用

併發 多個任務同一時間段進行 並行 多個任務同一時刻進行 執行緒的實現 執行緒模組 python通過兩個標準庫 thread 和threading,提供對執行緒的支援 threading對 thread進行了封裝 因此在實際的使用中我們一般都是使用threading threading模組中提供了t...