多线程对全局变量修改和单线程对全局变量修改

线程过多了,不会比单线程快多少。因为程序可能花时间在线程的转换上了。threading模块没有返回值。

import threading
import time
ind=4
dan_sum=0
multi_sum=0
def single():
    for j in range(ind):
        for i in range(5000):
            print(i*2)
            global dan_sum
            dan_sum=dan_sum+i*2
def s():
    for i in range(5000):
        print(i*2)
        global multi_sum
        multi_sum=multi_sum+i*2
def multi():
    threa=[]
    for j in range(ind):
        threa.append(threading.Thread(target=s))
    for t in threa:
        t.start()
    for t in threa:
        t.join()
if __name__ == '__main__':
    start=time.time()
    single()
    end=time.time()
    sum=0
    sum1=0
    sum=end-start
    start=time.time()
    multi()
    end=time.time()
    sum1=end-start
    print('single',sum,'multi',sum1,dan_sum,multi_sum)
posted @ 2023-05-03 10:00  祥瑞哈哈哈  阅读(108)  评论(0编辑  收藏  举报