python多執行緒練習題

2021-08-20 07:32:17 字數 2373 閱讀 1739

多執行緒練習題目,涉及知識點較多,屬於很好的練習題。

通過多執行緒實現類似linux中的>>功能,也就是將日誌記錄到指定的檔案中。

基本為main.py寫主要處理邏輯,utils.py構造工具類及對應的方法。

main.py

定義server()類,類中定義方法輸出內容。

例項化工具類,啟動執行緒,設定標準輸出和錯誤輸出至日誌檔案。

例項化server()類並呼叫方法進行內容的持續輸出。

utils.py

定義工具類,工具類需要傳入引數:日誌名稱。

首先判斷日誌是否存在,若不存在則建立,然後寫入日誌;存在則追加寫入日誌。

main.py

123

4567

891011

1213

1415

1617

18

import sys

from queue1.log_out.utils import tracelog

class

server

(object):

deflog

(self):

print("start server")

for i in range(100):

print(i)

print("end server") #print的實現是呼叫sys.stdout.write()方法

if __name__ == "__main__":

tracelog = tracelog("main.log")

tracelog.start()

sys.stdout = tracelog

sys.stderr = tracelog

server = server()

server.log() #print將會呼叫tracelog.write()方法

utils.py

123

4567

891011

1213

1415

1617

1819

2021

2223

2425

2627

2829

30

import codecs

from threading import thread, lock

import os

class

tracelog

(thread):

def__init__

(self, logname):

super(tracelog, self).__init__() #呼叫父類的初始化方法

self.logname = logname

self.lock = lock()

self.contexts =

self.isfile()

defisfile

(self):

ifnot os.path.exists(self.logname):

with codecs.open(self.logname, 'w') as f:

f.write("this log name is :\n".format(self.logname))

f.write("start log\n")

defwrite

(self, context):

defrun

(self):

while

1:self.lock.acquire()

if len(self.contexts) != 0:

with codecs.open(self.logname, 'a') as f: #追加方式寫入檔案

for context in self.contexts:

f.write(context)

del self.contexts[:] #每次寫入完成後清空列表

self.lock.release()

輸出結果

當前目錄下會生成main.log檔案,檔案內容如下

123

4567

891011

this log name is :main.log

start log

start server01

2..98

99end server

涉及檔案讀寫、鎖、多執行緒、sys模組、os模組等內容。

多執行緒練習題

注意要點 進入pthread cond wait之前必須加互斥鎖,以防止多執行緒同時請求pthread cond wait。在進入pthread cond wait後等待時,該函式會將互斥鎖解鎖。在離開pthread cond wait前,又會從新加鎖。include include include...

多執行緒練習題

寫兩個執行緒,乙個執行緒列印1 52,另乙個執行緒列印a z 列印順序為 12a34b56c 5152z class print catch interruptedexception e system.out.print 2 count 1 system.out.print 2 count flag...

求素數 多執行緒練習題

編寫乙個有兩個執行緒的程式,第乙個執行緒用來計算2 100000之間的素數的個數,第二個執行緒用來計算100000 200000之間的素數的個數,最後輸出結果。實現 package com.thread public class sushudemo1 extends thread override ...