在线程上运行函数会产生错误

时间:2019-01-10 04:10:12

标签: python-3.x multithreading

我正在尝试在带有三个参数的线程上运行函数“ generate_model”。

def thread_for_generate_model(Thread):
    def __init__(self, name, job_id, boolean_string, Batch_size):
        self.name = name
        self.job_id = job_id
        self.boolean_string = boolean_string
        self.Batch_size = Batch_size

    def run(self):
        LOGGER.info("vector model create started for job_id: %s on thread %s", self.job_id, self.name)
        generate_model(self.job_id, self.boolean_string, self.Batch_size)
        LOGGER.info("vector model created for job_id: %s", self.job_id)

def main(): 
     ....
     thread_for_generate_model("Thread_for_vectormodel", job_id, generate_search_string(job_id,keywords), 5000).start()
     # I am trying to run this function on a thread
     # generate_model(job_id, generate_search_string(job_id,keywords), 5000)
     ....

我出错了,

TypeError: thread_for_generate_model() takes 1 positional argument but 4 were given

通过link中的解决方案,我通过添加附加参数进行了如下修改

 def run(self, event=  None)

,但仍然存在相同的错误。怎么纠正呢?

1 个答案:

答案 0 :(得分:1)

下面的代码应该可以完成您想做的事情-我刚刚添加了一些虚拟函数等,以使代码不会引发语法错误或未定义的函数/变量等。这大致就是您可以遵循的结构。

如注释中所指出-使用def something定义方法。和class Something来定义一个类。

from threading import Thread
import logging
import time

LOGGER = logging.getLogger()
logging.basicConfig()

class thread_for_generate_model(Thread):
    def __init__(self, name, job_id, boolean_string, Batch_size):
        Thread.__init__(self)
        self.name = name
        self.job_id = job_id
        self.boolean_string = boolean_string
        self.Batch_size = Batch_size

    def run(self):
        LOGGER.info("vector model create started for job_id: %s on thread %s", self.job_id, self.name)
        generate_model(self.job_id, self.boolean_string, self.Batch_size)
        LOGGER.info("vector model created for job_id: %s", self.job_id)

def generate_search_string(job_id, keywords):
    return False

def generate_model(job_id, string, batch_size):
    while True:
        time.sleep(1)
def main():

    job_id = 0
    keywords = ['a', 'b']
    thread_for_generate_model("Thread_for_vectormodel", job_id, generate_search_string(job_id,keywords), 5000).start()
    # I am trying to run this function on a thread
    # generate_model(job_id, generate_search_string(job_id,keywords), 5000)


if __name__ == '__main__':
        main()