執行緒和程序 python的多執行緒

2022-09-13 11:42:11 字數 3746 閱讀 3581

首先要分清楚這兩個概念。

程序:乙個具有獨立功能的程式關於某個資料集合的一次執行活動。其一,它是乙個實體;其二,是乙個「執行中的程式」。

執行緒:程序裡包含的執行單元叫執行緒,乙個程序可以包含多個執行緒。它是cpu的基本排程單位。

乙個程序的記憶體空間是可以被它的執行緒共享的,但是乙個執行緒在使用時,其它執行緒必須等待。通過「鎖」防止多個執行緒同時占用空間。

在不同執行緒同時訪問時,資料的保護機制是怎樣的呢?這就要提到python的乙個「鎖」——gil(全稱為全域性直譯器鎖),要想利用多核系統,python必須支援多執行緒執行。作為解釋型語言,python的直譯器必須做到既安全又高效。我們都知道多執行緒程式設計會遇到的問題。直譯器要留意的是避免在不同的執行緒操作內部共享的資料。同時它還要保證在管理使用者執行緒時保證總是有最大化的計算資源。所以python就有了這麼乙個「鎖」。這是乙個讓人頭疼的問題,「鎖」的存在解決了那一些麻煩,但是也犧牲了python的多執行緒能力。

python的多執行緒適合於:大量密集的i/o處理

python的多程序:大量的密集平行計算

儘管python的多執行緒功能看起來比較雞肋,但是在爬蟲中的應用,還是可以提高效率的。

1

import

requests

2import threading #

使用執行緒庫

3from queue import

queue

4from lxml import

etree

5import

json

6import

time78

9class

threadcrawl(threading.thread):

10def

__init__

(self,threadname,pagequeue,dataqueue):

1112 threading.thread.__init__

(self)13#

呼叫父類初始化方法14#

super(threadcrawl,self).__init__()

15 self.threadname=threadname

16 self.pagequeue=pagequeue

17 self.dataqueue=dataqueue

18 self.headers=

1920

21def

run(self):

22pass

23self.dataqueue.put(content)

2425

except:26

pass

27print("

結束" +self.threadname)

2829

class

threadparse(threading.thread):

30def

__init__

(self,threadname,dataqueue,filename,lock):

31 super(threadparse,self).__init__

()32 self.threadname=threadname

33 self.dataqueue=dataqueue

34 self.filename=filename

35 self.lock=lock

3637

38def

run(self):

39pass

4041

defparse(self,html):

42pass

43with self.lock:

44 self.filename.write(json.dumps(items,ensure_ascii=false).encoding("

utf-8

") + "\n"

)454647

4849 grasp_exit=false

50 parse_exit=false

5152

5354

defmain():55#

設定頁碼佇列

56 pagequeue=queue(20)57#

放入1-10個數字,按照佇列的先進先出原則

58for i in range(1,21):

59pagequeue.put(i)

6061

#採集結果的佇列,為空則表示無限制

62 dataqueue=queue()

6364 filename=open("

lagou.json

","a")

6566

#建立鎖

67 lock=threading.lock()

686970#

採集執行緒

71 grasplist=["

採集執行緒1

","採集執行緒2

","採集執行緒3"]

72#儲存執行緒

73 threadcrawl=

74for threadname in

grasplist:

75 thread=threadcrawl(threadname,pagequeue,dataqueue)

76thread.start()

777879#

解析執行緒

80 parselist=["

解析執行緒1

","解析執行緒2

","解析執行緒3"]

81#儲存執行緒

82 threadparse=

83for threadname in

parselist:

84 thread=threadparse(threadname,dataqueue,filename,lock)

85thread.start()

8687

88while

notpagequeue.empty():

89pass

9091

92global

grasp_exit

93 grasp_exit=true

9495

print("

隊列為空")

多執行緒能提高的效率是有限的,後期會使用非同步網路框架如scrapy來提高爬蟲效率。

python筆記 程序和執行緒 多執行緒

一 建立乙個多程序 啟動乙個執行緒就是把乙個函式傳入並建立thread例項,然後呼叫start 開始執行 1.1 及執行結果 如以上 所示,threading.current thread 返回程序例項,用threading.current thread name返回例項名稱,主線程例項的名字叫ma...

Python多執行緒 程序

一 執行緒 程序 對於作業系統來說,乙個任務就是乙個程序 process 比如開啟乙個瀏覽器就是啟動乙個瀏覽器程序,開啟乙個記事本就啟動了乙個記事本程序,開啟兩個記事本就啟動了兩個記事本程序,開啟乙個word就啟動了乙個word程序。程序是很多資源的集合。有些程序還不止同時幹一件事,比如word,它...

python 多執行緒 和 多程序

單執行緒例子 usr bin python coding utf 8 name danxiancheng.py import time import threading def loop num,sec print loop s start num,time.strftime y m d h m s...