用类调用线程

时间:2017-10-01 21:28:36

标签: multithreading python-3.x class for-loop parallel-processing

我不想与DictionaryTagger类中的文件并行。 我在课堂上传递了5个文件,

class DictionaryTagger(object):
    print_look = threading.Lock()
    def __init__(self, dictionary_paths):

      print('Hilo:', threading.current_thread().getName())
      files = [open(path, 'r') for path in dictionary_paths]
      dictionaries = [yaml.load(dict_file) for dict_file in files]
      map(lambda x: x.close(), files)
      self.dictionary = {}
      self.max_key_size = 0
      for curr_dict in dictionaries:
         #print(curr_dict)
         for key in curr_dict:
            #print(type(curr_dict))
            #self.dictionary = 
              if key in self.dictionary:
                  self.dictionary[key].extend(curr_dict[key])
              else:
                  self.dictionary[key] = curr_dict[key]
                  self.max_key_size = max(self.max_key_size, len(key))
   dictt = DictionaryTagger(['dicts/positive22.yml', 'dicts/negative22.yml', 'dicts/increasers.yml', 'dicts/decreasers.yml', 'dicts/inverter.yml']) 

当我通过这个时,我有一个错误,因为'dictionary_paths'没有定义。

for i in range(3):
   t = threading.Thread(target=DictionaryTagger)
   t.demond = True
   t.start()

init ()缺少1个必需的位置参数:'_ictionary_paths''

1 个答案:

答案 0 :(得分:0)

您收到此错误是因为 init 函数您定义为参数(' dictionary_paths')而没有默认值。您可以通过两种不同的方式解决此问题:

  1. init 功能

    添加默认值
    default_dictionary_paths = []
    for i in range(3):
        t = threading.Thread(target=DictionaryTagger, args=(default_dictionary_paths))
        t.demond = True
        t.start()
    
  2. 在开始threads时提供参数:

    from flask import *
    
    app = Flask(__name__)
    
    @app.route("/music",methods=['GET'])
    def music():
        return "<h1>Hello, {0}</h1>".format(request.args.get('name'))
    
    @app.route("/",methods=['GET'])
    def index():
        return "<h1>Hello, {0}</h1>".format(request.args.get('name'))
    
    if __name__ == '__main__':
        app.run(host='localhost', port=40000,debug=True)