前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >20.multi_case03

20.multi_case03

作者头像
hankleo
发布2020-09-17 11:06:06
2010
发布2020-09-17 11:06:06
举报
文章被收录于专栏:Hank’s BlogHank’s Blog
代码语言:javascript
复制
# 多线程
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")
代码语言:javascript
复制
import threadpool
import time

def sayhello(a):
    print("hello: " + a)
    time.sleep(2)

def main():
    global result
    seed = ["a", "b", "c"]
    start = time.time()
    task_pool = threadpool.ThreadPool(5)
    requests = threadpool.makeRequests(sayhello, seed)
    for req in requests:
        task_pool.putRequest(req)
    task_pool.wait()
    end = time.time()
    time_m = end - start
    print("time: " + str(time_m))
    start1 = time.time()
    for each in seed:
        sayhello(each)
    end1 = time.time()
    print("time1: " + str(end1 - start1))

if __name__ == '__main__':
    main()
代码语言:javascript
复制
from concurrent.futures import ThreadPoolExecutor
import time

def sayhello(a):
    print("hello: " + a)
    time.sleep(2)

def main():
    seed = ["a", "b", "c"]
    start1 = time.time()
    for each in seed:
        sayhello(each)
    end1 = time.time()
    print("time1: " + str(end1 - start1))
    start2 = time.time()
    with ThreadPoolExecutor(3) as executor:
        for each in seed:
            executor.submit(sayhello, each)
    end2 = time.time()
    print("time2: " + str(end2 - start2))
    start3 = time.time()
    with ThreadPoolExecutor(3) as executor1:
        executor1.map(sayhello, seed)
    end3 = time.time()
    print("time3: " + str(end3 - start3))

if __name__ == '__main__':
    main()
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-05-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档