运行类方法在螺纹(蟒)(Run Class methods in threads (python))

2019-07-21 09:48发布

目前,我正在学习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

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

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

r = DomainOperations('google.com')

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

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

但是,我应该使用它们的类之外? 我应该写另一个类来处理线程?

什么是这样做的正确方法

Answer 1:

如果你从类打电话给他们,这是非常简单:

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()


Answer 2:

你可以继承Thread类的DomainOperation,这样代码会更干净,易于理解。 你必须重写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)

你会以这种方式开始新的线程。

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


Answer 3:

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()

我不知道如何调用一个方法在一类,尤其是如果它有初始化参数,但你可以试试这个方法。我试图用多个进程来解决这个问题吧。



文章来源: Run Class methods in threads (python)