python 多线程

import threading
import time
def func(times,name):
    for i in range(times):
        print(name+'   run:  ' +str(i) +'\n')
        time.sleep(1)

if __name__=='__main__':
    thread_pool=[]

    ret={}
    th_1=threading.Thread(target=func,args=[5,'th_1'],name='th_1')
    th_2=threading.Thread(target=func,args=[5,'th_2'],name='th_2')

    thread_pool.append(th_1)
    thread_pool.append(th_2)

    print('主线程开始')
    for th in thread_pool:
        th.start()
    for th in thread_pool:
        th.join()
    print('主线程结束')
import threading

class ThreadChild(threading.Thread):
    def __init__(self,times,name):
        threading.Thread.__init__(self)
        self.times=times
        self.name=name
    def run(self):
        for i in range(self.times):
            print('{} run: {}'.format(self.name,i))

if __name__=='__main__':
    thread_pool=[]
    th_1=ThreadChild(times=3,name='th_1')
    th_2=ThreadChild(times=3,name='th_2')

    thread_pool.append(th_2)
    thread_pool.append(th_1)
    for th in thread_pool:
        th.start()
    for th in thread_pool:
        th.join()
    print('主线程结束')
import threading
import time


class ThreadChild(threading.Thread):

    def __init__(self, times, name, ret, ret_lock):
        threading.Thread.__init__(self)
        self.times = times
        self.name = name
        self.ret = ret
        self.ret_lock = ret_lock
        return

    def run(self):
        for i in range(self.times):
            print(self.name + ' run: ' + str(i))
            time.sleep(1)
        self.ret_lock.acquire()
        # 进入有可能竞争的共享资源,锁住
        self.ret[self.name] = self.name + " finished with " + str(self.times) + " times printed"
        # 共享资源读写结束,开锁
        self.ret_lock.release()
        return


if __name__ == '__main__':

    thread_pool = []
    ret = {}
    ret_lock = threading.Lock()
    th_1 = ThreadChild(times=3, name='th_1', ret=ret, ret_lock=ret_lock)
    th_2 = ThreadChild(times=5, name='th_2', ret=ret, ret_lock=ret_lock)
    thread_pool.append(th_1)
    thread_pool.append(th_2)

    for th in thread_pool:
        th.start()

    for th in thread_pool:
        th.join()

    print(ret)
import threading
import math
import datetime


class ThreadChild(threading.Thread):

    def __init__(self, num_list, name, ret, ret_lock):
        threading.Thread.__init__(self)
        self.num_list = num_list
        self.name = name
        self.ret = ret
        self.ret_lock = ret_lock


    def run(self):
        result = 0
        for num in self.num_list:
            result += math.sqrt(num * math.tanh(num) / math.log2(num) / math.log10(num))
        self.ret_lock.acquire()
        self.ret[self.name] = result
        self.ret_lock.release()



if __name__ == '__main__':

    thread_pool = []
    ret = {}
    ret_lock = threading.Lock()
    th_1 = ThreadChild(num_list=list(range(10, 3000000)), name='th_1', ret=ret, ret_lock=ret_lock)
    th_2 = ThreadChild(num_list=list(range(3000000, 6000000)), name='th_2', ret=ret, ret_lock=ret_lock)
    th_3 = ThreadChild(num_list=list(range(6000000, 9000000)), name='th_3', ret=ret, ret_lock=ret_lock)
    thread_pool.append(th_1)
    thread_pool.append(th_2)
    thread_pool.append(th_3)

    start_t = datetime.datetime.now()

    for th in thread_pool:
        th.start()

    for th in thread_pool:
        th.join()

    final_result = sum(ret.values())
    end_t = datetime.datetime.now()
    elapsed_sec = (end_t - start_t).total_seconds()
    print("多线程计算结果: " + "{:.1f}".format(final_result) + ", 共消耗: " + "{:.2f}".format(elapsed_sec) + " 秒")

    ret.clear()
    th_4 = ThreadChild(num_list=list(range(10, 9000000)), name='th_4', ret=ret, ret_lock=ret_lock)
    start_t = datetime.datetime.now()
    th_4.start()
    th_4.join()
    final_result = sum(ret.values())
    end_t = datetime.datetime.now()
    elapsed_sec = (end_t - start_t).total_seconds()
    print("单线程计算结果: " + "{:.1f}".format(final_result) + ", 共消耗: " + "{:.2f}".format(elapsed_sec) + " 秒")

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一壶浊酒..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值