python多线程输出信息

时间:2016-06-05 08:40:29

标签: python multithreading

完整代码(来自github链接页面下方):

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import threading
import time
import random
import copy

exitFlag = 0

class checkup (threading.Thread):  #繼承thred 檢查流程
  def __init__(self, threadID, patientList, patientStatus):
    threading.Thread.__init__(self)
    self.threadID = threadID
    self.patientList = patientList
    self.patientStatus = patientStatus
  def run(self):                   #檢查中
    while True:
      if(check(self.patientList)):
        break
      for i in range( 0, 2, 1):
        for status in self.patientStatus:
          if status['name'] == self.patientList[i]['name'] and status['status'] == False and self.patientList[i]['status'] == False:
            status['status'] = True
            checkTime = random.randint(1,3)
            print "%s: %s check time(%d)" % (self.patientList[i]['name'], self.threadID, checkTime)
            time.sleep(checkTime)
            self.patientList[i]['status'] = True
            status['status'] = False
            time.sleep(1)

#check all patients have to be ckecked
def check(patientList):
  checkFlag = False
  for patient in patientList:
    if patient['status'] == True:
      checkFlag = True
    else:
      checkFlag = False
  if checkFlag:
    return True
  else:
    return False

# patients init
patients = [{
  'name': 'Kevin',
  'status': False
},{
  'name': 'Tom',
  'status': False
}]

# Outpatient init
random.shuffle(patients)
Cardiology = {
  'name': 'Cardiology',
  'patientList':  copy.deepcopy(patients),
  'patientStatus': patients
}
CardiologyCheckup = checkup('Cardiology', Cardiology['patientList'], Cardiology['patientStatus'])

random.shuffle(patients)
Chest = {
  'name': 'Chest',
  'patientList':  copy.deepcopy(patients),
  'patientStatus': patients
}
ChestCheckup = checkup('Chest', Chest['patientList'], Chest['patientStatus'])

ChestCheckup.start()
CardiologyCheckup.start()

来源:[https://github.com/stevekevin1005/OS/blob/master/os.py]

我想要它的输出:

Tom: Chest check time(1)
Kevin: Cardiology check time(2)
Kevin: Chest check time(1)
Tom: Cardiology check time(1)

但有时候:

Kevin: Chest check time(2)
Tom: Cardiology check time(3)
Tom: Chest check time(1)

只需三行

我犯了什么错误?

如何创建像对象一样的元素? 离。

a={
 'a': 1,
 'b': 2
}
#a[a] 1
#a[b] 2

1 个答案:

答案 0 :(得分:0)

因此,这里承诺的是PEP8 ok版本(注意也改变了变量中的名称和使用的dicts的键)。它应该 - 除了回答这个问题 - 帮助OP解决转变(正如@MoonCheesez在评论中所建议的那样)。

请注意,我还删除了未处理的exitFlag模块级变量,简化了一些逻辑评估w.r.t.假,真,并使用** kwargs使参数链更容易在眼睛上。

另请注意,我解释了将所有这些变量与False或True进行比较的意愿并未最好地表示为"为False" (例如)但实际上只是真实性或虚假性。

所以这里有一个pepified版本:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""Explain here what this module has to offer."""
from __future__ import print_function
import copy
import random
import sys
import threading
import time


class CheckUp(threading.Thread):
    """Explain here what this class represents and some usage hints."""
    def __init__(self, **kwargs):
        threading.Thread.__init__(self)
        self.threadID = kwargs['area_name']
        self.patient_list = kwargs['patient_list']
        self.patients_w_status = kwargs['patients_w_status']

    def run(self):
        """Describe logic of processing here."""
        s_k, n_k = 'status', 'name'
        busy_sleep_secs = 1
        while True:
            if check(self.patient_list):
                break
            for i in range(0, 2, 1):
                for status in self.patients_w_status:
                    if status[n_k] == self.patient_list[i][n_k]:
                        if not (status[s_k] or self.patient_list[i][s_k]):
                            status[s_k] = True
                            check_time = random.randint(1, 3)
                            print("%s: %s check time(%d)"
                                  "" % (self.patient_list[i][n_k],
                                        self.threadID, check_time))
                            time.sleep(check_time)
                            self.patient_list[i][s_k] = True
                            status[s_k] = False
                            time.sleep(busy_sleep_secs)


def check(patient_list):
    """Check all patients have to be checked."""
    check_flag = False
    for patient in patient_list:
        check_flag = True if patient['status'] else False
    return check_flag


def main():
    """Drive the endeavour."""
    # patients init
    patients = [{
        'name': 'Kevin',
        'status': False
    }, {
        'name': 'Tom',
        'status': False
    }]

    # Outpatient init
    random.shuffle(patients)
    cardiology = {
        'area_name': 'Cardiology',
        'patient_list': copy.deepcopy(patients),
        'patients_w_status': copy.deepcopy(patients)
    }
    cardiologyCheckup = CheckUp(**cardiology)

    random.shuffle(patients)
    chest = {
        'area_name': 'Chest',
        'patient_list': copy.deepcopy(patients),
        'patients_w_status': copy.deepcopy(patients)
    }
    chestCheckup = CheckUp(**chest)

    chestCheckup.start()
    cardiologyCheckup.start()


if __name__ == '__main__':
    sys.exit(main())

调用时不使用copy.deepcopy(patients)作为dicts中patients_w_status键的值:

$> python2 so_threading_output.py
Kevin: Chest check time(1)
Tom: Cardiology check time(2)
Tom: Chest check time(2)

$> python2 so_threading_output.py
Kevin: Chest check time(3)
Tom: Cardiology check time(1)
Tom: Chest check time(3)

当使用上面更正的版本时,也会将患者dict深度复制到patients_w_status关键字段中:

$> python2 so_threading_output.py
Tom: Chest check time(3)
Tom: Cardiology check time(2)
Kevin: Cardiology check time(1)
Kevin: Chest check time(3)

$> python2 so_threading_output.py
Kevin: Chest check time(3)
Tom: Cardiology check time(3)
Kevin: Cardiology check time(2)
Tom: Chest check time(2)

这是否解决了这个问题。它看起来像是,因为似乎没有理由深刻地复制一个字典而浅层复制另一个当它以某种方式被处理时。