Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在线程中运行类方法(python)_Python_Multithreading_Class_Methods - Fatal编程技术网

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

在线程中运行类方法(python),python,multithreading,class,methods,Python,Multithreading,Class,Methods,我目前正在学习Python和类,我有一个基本问题,但我没有找到任何答案。假设我有一个虚拟类 class DomainOperations: def __init__(self, domain): self.domain = domain self.domain_ip = '' self.website_thumbnail = '' def resolve_domain(self): #resolve domain

我目前正在学习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_缩略图,当线程完成后,我想打印IP和缩略图

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

r = DomainOperations('google.com')

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

t2 = threading.Thread(target=r.generate_website_thumbnail)
t2.start()
但是我应该在课外使用它们吗?我应该编写另一个类来处理线程吗


做这件事的正确方法是什么?

如果你在课堂上给他们打电话,很简单:

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

您可以在DomainOperation中继承Thread类,这样代码将更干净,更容易理解。必须重写run()方法

您将以这种方式启动线程

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

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

-1:您可以在类中运行线程,但所述线程不会继承“self”命名空间。所以基本上你不能。有点重要info@jasondancks对不起,你错了。请查看以下示例:
self.resolve\u domain
self.generate\u website\u缩略图
将使用对象属性,因为
self
是这两个调用的第一个参数。我今天无法在代码中实现这一点,因此我必须将我的方法从类中取出,并将对象作为参数传递。很抱歉。@A.Rodas pastebin不再可用。有没有其他方法可以得到这个例子?thanks@SergioMorstabilini我已经更新了这个片段,希望对你有所帮助!想知道如果你用
args=(r,)
另外构造线程,它是否会起作用。这将与RuntimeError:thread一起出错。如果没有调用,你需要添加super(DomainOperations,self)。\uuuuu init(self)到init请翻译中文注释
if __name__ == '__main__':
   thread1 = DomainOperations()
   thread1.start()
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()