python 中使用线程有两种方式:函数或者用类来包装线程对象。

函数式:

调用 thread 模块中的start_new_thread()函数来产生新线程。

语法如下:

thread.start_new_thread(function, args[, kwargs])

参数说明:

  • function – 线程函数。
  • args – 传递给线程函数的参数,它必须是个 tuple 类型。
  • kwargs – 可选参数。
import thread
import time
 
# 为线程定义一个函数
def print_time(threadname, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print ("%s: %s" % (threadname, time.ctime(time.time())))
 
# 创建两个线程
try:
   thread.start_new_thread(print_time, ("thread-1", 2,))
   thread.start_new_thread(print_time, ("thread-2", 4,))
except:
   print ("error: unable to start thread")
 
while 1:
   pass

使用 threading 模块创建线程

使用 threading模块创建线程,直接从 threading.thread 继承,然后重写__init__方法和 run 方法:

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")

线程同步

如果多个线程共同对某个数据修改,则可能出现不可预料的结果,为了保证数据的正确性,需要对多个线程进行同步。

使用 thread 对象的 lock 和 rlock 可以实现简单的线程同步,这两个对象都有 acquire 方法和 release 方法,对于那些需要每次只允许一个线程操作的数据,可以将其操作放到 acquire 和 release 方法之间。如下:

import threading
import time
 
class mythread (threading.thread):
    def __init__(self, threadid, name, counter):
        threading.thread.__init__(self)
        self.threadid = threadid
        self.name = name
        self.counter = counter
    def run(self):
        print ("starting " + self.name)
       # 获得锁,成功获得锁定后返回true
       # 可选的timeout参数不填时将一直阻塞直到获得锁定
       # 否则超时后将返回false
        threadlock.acquire()
        print_time(self.name, self.counter, 3)
        # 释放锁
        threadlock.release()
 
def print_time(threadname, delay, counter):
    while counter:
        time.sleep(delay)
        print ("%s: %s" % (threadname, time.ctime(time.time())))
        counter -= 1
 
threadlock = threading.lock()
threads = []
 
# 创建新线程
thread1 = mythread(1, "thread-1", 1)
thread2 = mythread(2, "thread-2", 2)
 
# 开启新线程
thread1.start()
thread2.start()
 
# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)
 
# 等待所有线程完成
for t in threads:
    t.join()
print ("exiting main thread")

线程优先级队列(queue)

python 的 queue 模块中提供了同步的、线程安全的队列类,包括 fifo(先入先出)队列 queue,lifo(后入先出)队列 lifoqueue 和优先级队列 priorityqueue。这些队列都实现了锁原语,能够在多线程中直接使用。可以使用队列来实现线程间的同步。

queue 模块中的常用方法:

  • queue.qsize() 返回队列的大小
  • queue.empty() 如果队列为空,返回true,反之false
  • queue.full() 如果队列满了,返回true,反之false
  • queue.full 与 maxsize 大小对应
  • queue.get([block[, timeout]])获取队列,timeout等待时间
  • queue.get_nowait() 相当queue.get(false)
  • queue.put(item) 写入队列,timeout等待时间
  • queue.put_nowait(item) 相当queue.put(item, false)
  • queue.task_done() 在完成一项工作之后,queue.task_done()函数向任务已经完成的队列发送一个信号
  • queue.join() 实际上意味着等到队列为空,再执行别的操作
import queue
import threading
import time
 
exitflag = 0
 
class mythread (threading.thread):
    def __init__(self, threadid, name, q):
        threading.thread.__init__(self)
        self.threadid = threadid
        self.name = name
        self.q = q
    def run(self):
        print ("starting " + self.name)
        process_data(self.name, self.q)
        print ("exiting " + self.name)
 
def process_data(threadname, q):
    while not exitflag:
        queuelock.acquire()
        if not workqueue.empty():
            data = q.get()
            queuelock.release()
            print ("%s processing %s" % (threadname, data))
        else:
            queuelock.release()
        time.sleep(1)
 
threadlist = ["thread-1", "thread-2", "thread-3"]
namelist = ["one", "two", "three", "four", "five"]
queuelock = threading.lock()
workqueue = queue.queue(10)
threads = []
threadid = 1
 
# 创建新线程
for tname in threadlist:
    thread = mythread(threadid, tname, workqueue)
    thread.start()
    threads.append(thread)
    threadid += 1
 
# 填充队列
queuelock.acquire()
for word in namelist:
    workqueue.put(word)
queuelock.release()
 
# 等待队列清空
while not workqueue.empty():
    pass
 
# 通知线程是时候退出
exitflag = 1
 
# 等待所有线程完成
for t in threads:
    t.join()
print ("exiting main thread")

到此这篇关于python多线程入门学习的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。