关于线程池思考

#coding=utf-8

import random
import string
import time
import threading
from threading import Lock

class MyThread(threading.Thread):
    def __init__(self, func,arg=()):
        # super(MyThread, self).__init__()
        threading.Thread.__init__(self)
        self.func = func
        self.arg=arg
        self.lock=Lock()
    def run(self):
        with self.lock:
            self.result=self.func(*self.arg)
        # self.result = self.func()
    def get_result(self):
        try:
            return self.result
        except Exception:
            return None
def get_generateId(x,y):
    strings = ''.join(random.sample(string.hexdigits, random.randint(x,y)))

    # strings=eggroll.generateUniqueId()
    return strings
def main(data_totalsNumber):
    st=time.time()
    thread_list = []
    list_sampleIds=[]
    for i in range(data_totalsNumber):
        t = MyThread(get_generateId,arg=(16,18))
        thread_list.append(t)
        t.start()
    for t in thread_list:
        t.join()
        list_sampleIds.append(t.get_result())
    # print(list_sampleIds)
    print(time.time()-st)
    # real_idNumbers= len(set(list_sampleIds))
    # assert real_idNumbers == data_totalsNumber
if __name__ == '__main__':
    main(data_totalsNumber=200000)
cost 85.71295762062073

  threadpool 模式线程池调用

import time
import threading

from concurrent.futures import ThreadPoolExecutor


class Account(object):
    """银行账户"""

    def __init__(self):
        self.balance = 0.0
        self.lock = threading.Lock()

    def deposit(self, money):
        # 通过锁保护临界资源
        with self.lock:

            new_balance = self.balance + money
            time.sleep(0.001)
            self.balance = new_balance


class AddMoneyThread(threading.Thread):
    """自定义线程类"""

    def __init__(self, account, money):
        self.account = account
        self.money = money
        # 自定义线程的初始化方法中必须调用父类的初始化方法
        super().__init__()

    def run(self):
        # 线程启动之后要执行的操作

        self.account.deposit(self.money)

def main():
    """主函数"""
    account = Account()
    # 创建线程池
    pool = ThreadPoolExecutor(max_workers=16)
    futures = []
    st = time.time()
    for _ in range(400):
        # 创建线程的第1种方式
        # threading.Thread(
        #     target=account.deposit, args=(1, )
        # ).start()
        # 创建线程的第2种方式
        # AddMoneyThread(account, 1).start()
        # 创建线程的第3种方式
        # 调用线程池中的线程来执行特定的任务
        future = pool.submit(account.deposit, 1)
        futures.append(future)
    # 关闭线程池
    pool.shutdown()

    for future in futures:
        future.result()
    print("cost time",time.time()-st)
    print(account.balance)

def main2():
    pass


if __name__ == '__main__':
    main()

  

转载于:https://www.cnblogs.com/SunshineKimi/p/11084735.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值