1. 程式人生 > 其它 >Python 面試題:執行緒

Python 面試題:執行緒

如何定義執行緒

  1. 使用建構函式

  def func(infile, outfile):
    f = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED)
    f.write(infile)
    f.close()
    print('Finished background zip of:', infile)


background = threading.Thread(target=func, args=('mydata.txt', 'myarchive.zip'))
  1. 子類化

import threading
import zipfile

class AsyncZip(threading.Thread):
    def __init__(self, infile, outfile):
        threading.Thread.__init__(self)
        self.infile = infile
        self.outfile = outfile

    def run(self):
        f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
        f.write(self.infile)
        f.close()
        print('Finished background zip of:', self.infile)


background = AsyncZip('mydata.txt', 'myarchive.zip')
background.start()
print('The main program continues to run in foreground.')

如何手動結束執行緒

  • 對於 IO 密集的工作,可以在程式碼中增加超時控制+狀態欄位,即 IO 超時結束後,根據狀態欄位結束執行緒。
  class IOTask:
    def terminate(self):
        self._running = False

    def run(self, sock):
        # sock is a socket
        sock.settimeout(5)        # Set timeout period
        while self._running:
            # Perform a blocking I/O operation w/ timeout
            try:
                data = sock.recv(8192)
                break
            except socket.timeout:
                continue
            # Continued processing
            ...
        # Terminated
        return 

執行緒間通訊有哪些方式

  • 鎖,重入鎖、事件、訊號量、佇列。從一個執行緒向另一個執行緒傳送資料最安全的方式可能就是使用 queue 庫中的隊列了,可以適用於消費者和生產者模型。
from queue import Queue
from threading import Thread

# A thread that produces data
def producer(out_q):
    while running:
        # Produce some data
        ...
        out_q.put(data)

# A thread that consumes data
def consumer(in_q):
    while True:
        # Get some data
        data = in_q.get()

        # Process the data
        ...
        # Indicate completion
        in_q.task_done()

# Create the shared queue and launch both threads
q = Queue()
t1 = Thread(target=consumer, args=(q,))
t2 = Thread(target=producer, args=(q,))
t1.start()
t2.start()

# Wait for all produced items to be consumed
q.join()