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()
posted @ 2022-03-20 17:20  profound-wu  阅读(85)  评论(0)    收藏  举报