在线程中运行类方法(python)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15365406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:54:59  来源:igfitidea点击:

Run Class methods in threads (python)

pythonmultithreadingclassmethods

提问by nacholibre

I'm currently learning Python and Classes and I have a basic question, but I didn't find any answer to it. Let's say I have this dummy class

我目前正在学习 Python 和类,我有一个基本问题,但我没有找到任何答案。假设我有这个虚拟课程

class DomainOperations:
    def __init__(self, domain):
        self.domain = domain
        self.domain_ip = ''
        self.website_thumbnail = ''

    def resolve_domain(self):
        #resolve domain to ipv4 and save to self.domain_ip

    def generate_website_thumbnail(self):
        #generate website thumbnail and save the url to self.website_thumbnail

I want to run simultaneously resolve_domain and generate_website_thumbnail and when the threads are finished I want to print the IP and the thumbnail.

我想同时运行 resolve_domain 和 generate_website_thumbnail,当线程完成时,我想打印 IP 和缩略图。

EDIT:I know I should use threads, maybe something like this

编辑:我知道我应该使用线程,也许是这样的

r = DomainOperations('google.com')

t1 = threading.Thread(target=r.resolve_domain)
t1.start()

t2 = threading.Thread(target=r.generate_website_thumbnail)
t2.start()

But should I use them outside the Class? Should I write another Class to handle Threads?

但是我应该在课堂之外使用它们吗?我应该编写另一个类来处理线程吗?

What is the right wayto do that?

这样做的正确方法是什么?

采纳答案by A. Rodas

If you call them from the class, it is as simple as:

如果您从类中调用它们,则很简单:

import threading

class DomainOperations:

    def __init__(self):
        self.domain_ip = ''
        self.website_thumbnail = ''

    def resolve_domain(self):
        self.domain_ip = 'foo'

    def generate_website_thumbnail(self):
        self.website_thumbnail= 'bar'

    def run(self):
        t1 = threading.Thread(target=self.resolve_domain)
        t2 = threading.Thread(target=self.generate_website_thumbnail)
        t1.start()
        t2.start()
        t1.join()
        t2.join()
        print(self.domain_ip, self.website_thumbnail)

if __name__ == '__main__':
    d = DomainOperations()
    d.run()

回答by Hafiz Hashim

You can inherit Thread class in DomainOperation, in this way code would be more clean and easily understandable. you have to override a run()method.

您可以在 DomainOperation 中继承 Thread 类,这样代码会更清晰易懂。你必须覆盖一个run()方法。

from threading import threading.Thread

class DomainOperations(Thread):
    def __init__(self):
       self.domain_ip = ''
       self.website_thumbnail = ''

   def resolve_domain(self):
       self.domain_ip = 'foo'

   def generate_website_thumbnail(self):
       self.website_thumbnail= 'bar'

   def run(self):
       #domain will be resolved on first thread
       self.resolve_domain()
       #thumbnail will be resolved on second OR newly created below thread
       thread2 = Thread(target=self.generate_website_thumbnail)
       thread.start()
       # thread1 will wait for thread2
       self.join()
       # thread2 will wait for thread1, if it's late.
       thread2.join()
       # here it will print ip and thumbnail before exiting first thread
       print(self.domain_ip, self.website_thumbnail)

And you will start your threads in this way.

您将以这种方式开始您的线程。

if __name__ == '__main__':
   thread1 = DomainOperations()
   thread1.start()

回答by user10845203

def post_test(tbid, line_num, response_time):
    """
    :param tbid: 参数id
    :return:
    """

    # 请求参数
    data = {'tbId': tbid, 'conditions': [{"key": "", "type": 1}], 'pageNum': 1, 'pageSize': 12}
    # 请求启动时间

    start = time.time()
    # post请求
    r = requests.post(url=url, data=json.dumps(data), headers=headers)
    # 请求结束时间
    end = time.time()
    # 保留两位小数
    finall_time = float('%.2f' % float(end - start))
    text = json.loads(r.text)
    # IO写入 只写入200的
    with open('text6.csv', 'a', newline='') as csvfile:
       if text['statusCode'] == '200':
        throughput = line_num * response_time / finall_time
        throughput = float('%.2f' % float(throughput))
        print('the perf_counter time of %s is %s and the content is %s ,throughput is %s' % (
            tbid, finall_time, json.loads(r.text), throughput))
        spamwriter = csv.writer(csvfile, dialect='excel')
        spamwriter.writerow([tbid] + [finall_time] + [throughput])
def start_thread(csv_name):
  tbid, response_time_sort, throughput_sort = read_csv(csv_name)
  print(tbid)
  line_num = len(tbid)
  response_times = 5

  for j in range(response_times):
    for i in tbid:
        t = threading.Thread(target=post_test, args=(i, line_num, response_times))
        t.start()
        t.join()

I don't know how to call a method in a class, especially if it has initialization parameters, but you can try this method。 I'm trying to use multiple processes to solve this problem, right。

我不知道如何调用类中的方法,特别是如果它有初始化参数,但是你可以试试这个方法。我正在尝试使用多个进程来解决这个问题,对吧。