Python基础——多线程(0524)

一、什么是线程

线程是操作系统能够进行运算调度的最小单位。

线程被包含在进程中,是进程中实际处理单位。一条线程就是一堆指令集合。

import threading
import time

def test1(threadName,delay):   #为线程定义一个函数
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print("进程{0},执行时间{1}".format(threadName,time.ctime(time.time())))
try:    #创建两个线程
    threading._start_new_thread(test1,("thread-1",2,))
    threading._start_new_thread(test1,("thread-2",4,))
except:
    print("Error:无法启动线程")
while 1:
    pass

运行结果

二、实现多进程的两种方式

1、将要执行的方法作为参数传递给  Thread  的构造方法。——用类来包装线程对象。

     即   t = threading.Thread(target=action, args=(i,))     其中action 指的是线程函数。

2、通过 继承  的方式实现!从 Thread 继承,并重写run() 方法。

三、线程模块常用的方法。

1、Python3 通过两个标准库 _thread 和 threading 提供对线程的支持。

2、threading 模块除了包含 _thread 模块中的所有方法外,还提供的其他方法:

     threading.currentThread(): 返回当前的线程变量

     threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。

     threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。

3、 Thread类 方法:

      3.1 run(): 用以表示线程活动的方法

      3.2 start():启动线程活动

      3.3 join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生

      3.4 isAlive(): 返回线程是否活动的

      3.5 getName(): 返回线程名

      3.6 setName(): 设置线程名

四、线程锁

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

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

3、锁有两种状态——锁定和未锁定。

4、语法格式:通过threading.Lock()来创建锁,函数在执行的时候先要获得锁,执行完以后要释放锁。

with lock:

lock.acquire()

lock.release()

5、示例

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 ("开启线程: " + self.name)
        # 获取锁,用于线程同步
        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 ("退出主线程")

运行结果

五、线程优先排队

1、Python 的 Queue 模块中提供了同步的、线程安全的队列类,包括FIFO(先入先出)队列Queue,LIFO(后入先出)队列LifoQueue,和优先级队列 PriorityQueue。

2、Queue 模块中的常用方法:

     2.1  Queue.qsize() 返回队列的大小

     2.2  Queue.empty() 如果队列为空,返回True,反之False

     2.3  Queue.full() 如果队列满了,返回True,反之False

     2.4  Queue.full 与 maxsize 大小对应

     2.5  Queue.get([block[, timeout]])获取队列,timeout等待时间

     2.6  Queue.get_nowait() 相当Queue.get(False)

     2.7  Queue.put(item) 写入队列,timeout等待时间

     2.8  Queue.put_nowait(item) 相当Queue.put(item, False)

     2.9  Queue.task_done() 在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号

     2.10  Queue.join() 实际上意味着等到队列为空,再执行别的操作

3、示例

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 ("开启线程:" + self.name)
        process_data(self.name, self.q)
        print ("退出线程:" + 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 ("退出主线程")

运行结果

猜你喜欢

转载自my.oschina.net/u/3821557/blog/1818880