Python多线程-货物工人模型

为了测试多线程效率,我写了一段货物工人模型代码,假如一个卡车上有20件货,每件货有重量,1kg花费1s,2kg花费2s,以此类推,以此模型建立代码如下:

# coding:utf-8
import threading
import time
from random import randint

# 货物源
goods = []
for n in range(20):
    goods.append(randint(1, 5))


# 工人货物模型
class MyThread(threading.Thread):

    def __init__(self, thread_id, name):
        threading.Thread.__init__(self)
        self.thread_id = thread_id
        self.name = name

    def run(self):
        print self.name + '开始工作'
        do_work(self.name)
        print self.name + '完成工作'


# 处理货物
def do_work(thread_name):
    while len(goods) > 0:
        if len(goods) > 0:
            # 从搬运货物的那一刻起货物就已经不存在货源了
            wight = goods[0]
            goods.remove(wight)
            time.sleep(wight)
            print thread_name + '花费了 ' + str(wight) + ' 秒'


# 工人
workers = ['张三']
threads = []
thread_id = 0

first_time = time.time()
for worker in workers:
    thread_id += 1
    thread = MyThread(thread_id, worker)
    thread.start()
    threads.append(thread)


# 等待所有线程完成
for t in threads:
    t.join()
last_time = time.time()
print "总耗时: " + str(last_time - first_time) + " 秒"

单工人工作效率:

张三开始工作
张三花费了 5 秒
张三花费了 3 秒
张三花费了 5 秒
张三花费了 4 秒
张三花费了 5 秒
张三花费了 1 秒
张三花费了 5 秒
张三花费了 4 秒
张三花费了 3 秒
张三花费了 3 秒
张三花费了 5 秒
张三花费了 3 秒
张三花费了 5 秒
张三花费了 5 秒
张三花费了 4 秒
张三花费了 4 秒
张三花费了 4 秒
张三花费了 1 秒
张三花费了 3 秒
张三花费了 2 秒
张三完成工作
总耗时: 74.0130000114 秒

改变工人数量增加到4个:

张三开始工作
李四开始工作
王五开始工作
赵六开始工作
张三花费了 1 秒 王五花费了 1 秒 

李四花费了 2 秒 
赵六花费了 2 秒 
王五花费了 3 秒 
李四花费了 3 秒 
张三花费了 5 秒 
赵六花费了 5 秒 李四花费了 2 秒 
 
王五花费了 3 秒 
赵六花费了 1 秒 
张三花费了 3 秒 
李四花费了 3 秒 
赵六花费了 2 秒 
张三花费了 2 秒 
李四花费了 1 秒 
王五花费了 5 秒 
王五完成工作
赵六花费了 4 秒 
赵六完成工作
张三花费了 5 秒 
张三完成工作
李四花费了 5 秒 
李四完成工作
总耗时: 16.004999876 秒

测试完成,效率杠杠的,当然可以考虑用这个模型来延申,比如工人成本,效率成本,这一批货物该找多少工人更划算。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值