http://blog.csdn.net/column/details/19679.html
import time
import _thread
# 线程 run 方法
def delay_print(thread_name, delay, print_content):
count = delay
while count >= 0:
print("[%s] %d sec" % (thread_name, count))
count -= 1
time.sleep(1)
print("[%s] %s" % (thread_name, print_content))
# 创建线程
_thread.start_new_thread(delay_print, ("Thread-1", 3, "Are you OK? Mi fans!"))
_thread.start_new_thread(delay_print, ("Thread-2", 5, "Derk dark ♂ fantastic"))
# 当前线程待命
while True:
pass
threading.currentThread() | 返回当前线程变量 |
threading.enumerate() | 返回一个包含正在运行线程的 list(即启动后、结束前的线程) |
threading.activeCount() |
返回正在运行的线程数量,同len(threading.enumerate()) |
Thread.isAive() | 检查线程是否活动 |
Thread.getName() | 获取线程名 |
Thread.setName() | 设置线程名 |
Thread.isDaemon() |
检查线程是否为后台线程 |
Thread.setDaemon() |
设置线程为后台线程 |
Thread.run() | 运行线程 |
Thread.start() | 启动线程 |
Thread.join([time]) | 当前线程等待至调用线程 Thread 结束或终止,这个阻塞直到 Thread.join() 方法调用终止(正常退出,或抛出未处理的异常,或可选参数中的超时发生) |
import time
import threading
# 线程实现类
class MyThread(threading.Thread):
def __init__(self, thread_name, delay, print_content):
threading.Thread.__init__(self)
self.thread_name = thread_name
self.delay = delay
self.print_content = print_content
def run(self):
count = self.delay
while count >= 0:
print("[%s] %d sec" % (self.thread_name, count))
count -= 1
time.sleep(1)
print("[%s] %s" % (self.thread_name, self.print_content))
# 创建线程
thread1 = MyThread("Thread-1", 3, "Are you OK? Mi fans!")
thread2 = MyThread("Thread-2", 3, "Derk dark ♂ fantastic")
# 运行线程
thread1.start()
thread2.start()
# 主线程阻塞直到2个线程执行结束
thread1.join()
thread2.join()
print("[Thead-main] all thread completed")
import time
import threading
# 线程实现类,通过一个私有变量 running 来标志运行状态
class MyThread(threading.Thread):
def __init__(self, delay):
threading.Thread.__init__(self)
self.delay = delay
self.__running = True
def interupt(self):
self.__running = False
print("thread is interrupt")
def run(self):
count = self.delay
while count >= 0 and self.__running:
print("%d sec" % count)
count -= 1
time.sleep(1)
print("thread running completed")
# 创建线程
thread1 = MyThread(10)
# 运行线程
thread1.start()
# 3s 后中断线程 thread1
time.sleep(3)
thread1.interupt()
# 示例多个线程获取一个共享资源,每次获取 Resource 并减少 Resource.__count 值
import random
import time
import threading
# 线程实现类
class MyThread(threading.Thread):
def __init__(self, thread_name, resource):
threading.Thread.__init__(self)
self.thread_name = thread_name
self.__resource = resource
def run(self):
# 获取资源起始数量
lock.acquire()
count = self.__resource.get_count()
lock.release()
while count >= 0:
# 获取资源,并修改 resource._count 值
lock.acquire()
count = self.__resource.get_count()
count -= 1
print("[%s] resource-count: %d" % (self.thread_name, count))
self.__resource.set_count(count)
lock.release()
# 模拟处理资源时间
time.sleep(random.random() * 3)
# 资源对象,储存线程共享资源
class Resource:
def __init__(self, count):
self.__count = count
def get_count(self):
return self.__count
def set_count(self, count):
self.__count = count
if __name__ == "__main__":
resource = Resource(100) # 创建资源(包含100个资源值)
lock = threading.Lock() # 创建线程锁对象
threadpool = list() # 使用一个list作为线程池
# 向线程池中添加 5 个线程
for i in range(1, 6):
threadpool.append(MyThread("Thread-"+str(i), resource))
# 运行线程池中的所有线程
for thread in threadpool:
thread.start()
for thread in threadpool:
thread.join()
Condition.acquire() |
调用线程获取锁 |
Condition.release() | 调用线程释放锁 |
Condition.wait([timeout]) | 调用线程释放锁,同时调用线程被挂起,直到被唤醒(或超时)时才重新获取锁,并继续执行下去; |
Condition.notify() | 唤醒任意一个挂起线程(如果存在挂起的线程),但是不会释放锁占用的锁 |
Confition.notifyAll() | 同上,不过唤醒所有挂起线程,所有线程重新开始竞争CPU时间 |
import random
import time
import threading
# 生产者线程
class Producer(threading.Thread):
def __init__(self, thread_name):
threading.Thread.__init__(self)
self.__thread_name = thread_name
def run(self):
while True:
product = random.randrange(0, 100, 10) # 模拟生产产品
time.sleep(random.random() * 2) # 模拟处理时间
condition.acquire()
resources.append(product) # 向资源列表添加产品
print("[%s] create product: %d , resource size: %d" % (self.__thread_name, product, len(resources)))
condition.notify() #唤醒一个挂起线程
condition.release()
# 消费者线程
class Consumer(threading.Thread):
def __init__(self, thread_name):
threading.Thread.__init__(self)
self.__thread_name = thread_name
def run(self):
while True:
condition.acquire()
if len(resources) <= 0: # 当资源列表为空时,线程挂起
condition.wait()
product = resources.pop() # 获取资源
print("[%s] get product: %d , resource size: %d" % (self.__thread_name, product, len(resources)))
condition.release()
# 模拟处理资源时间
time.sleep(random.random() * 8)
if __name__ == "__main__":
resources = list() # 资源列表对象
condition = threading.Condition()
threadpool = list() # 线程池对象
# 向线程池中添加 1 个生产者线程、3个消费者线程
threadpool.append(Producer("Productor-1"))
threadpool.append(Consumer("Consumer-1"))
threadpool.append(Consumer("Consumer-2"))
threadpool.append(Consumer("Consumer-3"))
# 运行线程池中的所有线程
for thread in threadpool:
thread.start()
for thread in threadpool:
thread.join()
Queue.qsize() |
返回队列的大小 |
Queue.empty() |
如果队列为空,返回True |
Queue.full() |
如果队列满了,返回True,与 maxsize 大小对应 |
Queue.get([block[, timeout]]) |
获取队列,timeout等待时间,block 为是否阻塞,默认为 True |
Queue.put(item [,block[, timeout]]) |
写入队列,timeout等待时间,block 为是否阻塞,默认为 True |
Queue.task_done() |
在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号 |
Queue.join() |
意味着等到队列为空,再执行别的操作 |
# 示例多个线程获取一个共享资源,每次获取 Resource 并减少 Resource.__count 值
import queue
import random
import time
import threading
# 生产者线程
class Producer(threading.Thread):
def __init__(self, thread_name):
threading.Thread.__init__(self)
self.__thread_name = thread_name
def run(self):
while True:
product = random.randrange(0, 100, 10) # 模拟生产产品
time.sleep(random.random() * 2) # 模拟处理时间
resources.put(product) # 向资源列表添加产品
print("[%s] create product: %d , resource size: %d" % (self.__thread_name, product, resources.qsize()))
# 消费者线程
class Consumer(threading.Thread):
def __init__(self, thread_name):
threading.Thread.__init__(self)
self.__thread_name = thread_name
def run(self):
while True:
product = resources.get() # 获取资源
print("[%s] get product: %d , resource size: %d" % (self.__thread_name, product, resources.qsize()))
# 模拟处理资源时间
time.sleep(random.random() * 8)
if __name__ == "__main__":
resources = queue.Queue(maxsize=15) # 使用同步队列作为资源储存
threadpool = list()
# 向线程池中添加 1 个生产者线程、3个消费者线程
threadpool.append(Producer("Productor-1"))
threadpool.append(Consumer("Consumer-1"))
threadpool.append(Consumer("Consumer-2"))
threadpool.append(Consumer("Consumer-3"))
# 运行线程池中的所有线程
for thread in threadpool:
thread.start()
for thread in threadpool:
thread.join()