python

python 多线程操作

2018-08-23  本文已影响4人  sunshaoping

1.Python标准库自带了两个多线程模块,分别是threading和thread,其中,thread是低级模块,threading是对thread的封装,一般,我们直接使用threading即可。下面来看一个简单的多线程例子:

# 利用threading模块使用多线程
def say_hello():  # 定义线程执行的函数
    print("Hello world!")

def run():
    start_time = time.time()  
    for i in range(10):
        thread = threading.Thread(target=say_hello)  # 定义线程执行函数
        thread.start()  # 启动线程
    end_time = time.time()
    times = end_time - start_time  # 计算线程执行时间
    print(times)

if __name__ == '__main__':
    run()

在这个例子中,我们首先定义了多线程执行的函数say_hello,然后我们在主函数中创建了10个线程,并告诉线程要执行的函数,然后我们调用start()方法启动这些线程
2.给线程传参数
通过定义并调用线程类,实现给线程传入参数功能

import threading

# 创建线程类
class sayHelloThread(threading.Thread):
    # 指定线程需要的参数name
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.name = name

    # 指定线程运行函数
    def run(self):
        print("%s say hello" %self.name) 
def main():
    # 创建线程
    thread_1 = sayHelloThread("Tom")
    # 启动线程
    thread_1.start()
    # 结束线程
    thread_1.join()

if __name__ == '__main__':
    main()

3.使用线程池
通过利用python内置的线程池,将将要执行的任务存放到线程池中,利用线程池来执行任务

# 线程池创建

import threadpool, time

# 创建任务
def say(name):
    print("%s say hello" % name)


def main():
    # 创建线程池,定义线程数为4
    pool = threadpool.ThreadPool(5)
    # 指定任务列表,里面一个元素代表着一个任务需要的参数
    tast_param_list = ["Tom", "Tim", "Roes", "Jim", "Jok"]
    # 创建任务列表
    task_list = threadpool.makeRequests(say, tast_param_list)
    start_time = int(time.time() * 1000)
    # 任务在线程池中执行
    [pool.putRequest(x) for x in task_list]
    # 等待任务执行完成
    pool.wait()
    end_time = int(time.time() * 1000)
    print("线程执行完毕,总共耗时%s" % ((end_time - start_time) / 1000))


if __name__ == '__main__':
    main()

4.产生线程队列

# 线程安全队列

import threading
# 线程队列
from queue import Queue
import time

# 创建线程安全的队列
queue = Queue(4)


# 创建生产线程类
class producerThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        index = 1
        while True:
            index += 1
            item = "item" + str(index)
            # 生产的item存放在队列
            queue.put(item)
            print("%s 生产:%s" % (threading.current_thread().getName(), item))
            time.sleep(1)


# 创建消费线程类
class customerThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        while True:
            # 从队列中获取数据
            item = queue.get()
            print("%s 消费:%s" % (threading.current_thread().getName(), item))


def main():
    # 创建生产者线程
    producer = producerThread()
    # 创建消费者线程
    customer = customerThread()
    # 启动生产者线程
    producer.start()
    # 启动消费者进程
    customer.start()


if __name__ == '__main__':
    main()

上一篇 下一篇

猜你喜欢

热点阅读