8.线程做进度条的,列表当做参数传递,线程关于全局变量的优缺点

#列表当做实参传递到线程中
import threading,time,random,copy
def work1(download_list,finish_list):
    #每次从当前下载列表当中去取第一个元素进行下载
    while True:
        file = download_list[0]
        print("--in work1--download:%d"%file)
        time.sleep(1)
        #自定默认删除最后一个
        # download_list.pop()
        #现在完成之后
        #1.任务列表中的移除已经下载的元素
        download_list.remove(file)
        #2.将已经完成的任务加到完成列表当中去
        finish_list.append(file)

        print(download_list,finish_list)
        if download_list == []:
            break

# def work2():
#     print("--in work2--")

if __name__ == "__main__":
    #下载任务列表
    downlist_list = [11,22,33]

    #完成任务列表
    finish_list = []

    t1 = threading.Thread(target=work1,args=(downlist_list,finish_list,))
    t1.start()

    # t2 = threading.Thread(target=work2,)
    # t2.start()

    #获取下载进度
    while True:
        pro = len(finish_list)/(len(downlist_list)+len(finish_list))
        print("当前下载进度:%.2f%%"%(pro*100))
        time.sleep(0.5)
        if pro == 1.00:
            break

#总结
#在一个进程内的所有线程共享全局变量,能够在不适用其他方式的前提下完成多线程之间的数据共享
#缺点:线程对全局变量的随意更改可能造成多线程之间的对全局变量引用比较混乱(线程安全就成了问题)

 

posted @ 2018-03-22 22:55  Bob__Zhang  阅读(276)  评论(0编辑  收藏  举报