Run Class methods in threads (python)

python thread class
python run function in thread
python thread join
python stop thread
how to make a thread run continuously in python
python thread callback
python thread communication
python thread timeout

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

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.

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

r = DomainOperations('')

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

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

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

What is the right way to do that?

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)
        print(self.domain_ip, self.website_thumbnail)

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

Python Multithreading Tutorial: Subclassing Thread, Python Multithread​​ As a Thread starts up, it does some basic initialization and then calls its run() method, which calls the target function passed to the constructor. The Thread class represents an activity that runs in a separate thread of control. Now all the functionality of Thread class will be inherited to our FileLoaderThread class. Thread class has a run() method that is invoked whenever we start the thread by calling start() function. Also, run() function in Thread class calls the callable entity (e.g. function) passed in target argument to execute that function in thread.

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.

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
       #thumbnail will be resolved on second OR newly created below thread
       thread2 = Thread(target=self.generate_website_thumbnail)
       # thread1 will wait for thread2
       # thread2 will wait for thread1, if it's late.
       # 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()

Running a method as a background thread in Python – Sebastian , I'll walk you through the most important parts. thread = threading. Thread(target=self. run, args=()) - Define which function to execute. thread. daemon = True - Run the thread in daemon mode. This allows the main application to exit even though the thread is running. thread. start() - Start the thread execution. Method Name: run() Method Overview: The run method designates thread body. The run method gets it code on two ways. One is when the run method is overridden in a subclass. Another is when a callable object is passed as a target through the constructor of the Thread class. Either way, one can formulate the run() method of a python thread.

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

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

    start = time.time()
    # post请求
    r =, 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)
  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))

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。

7.5.6 Thread Objects, In other words, only override the __init__() and run() methods of this class. Once a thread object is created, its activity must be started by calling the thread's this flag is that the entire Python program exits when only daemon threads are left. Now Python’s threading module provides a Thread class to create and manage threads. Thread class provides a constructor in which we can pass a callable entity i.e. function or member function etc and arguments require by that function in args i.e.

Python Thread Tutorial (Part 1), run() : This is the section where you can put your logic part. start() : The start() method starts a Python thread. The mythread class overrides the  Python also provides the threading module which implements a layer on top of the thread module. The threading module provides, among other things, a Thread class which contains a run () method. Typical usage is to subclass the Thread class and override the run () method in the subclass to implement the desired functionality. The Thread class

Create a Thread using Class in Python –, Thread class has a run() method that is invoked whenever we start the thread by calling start() function. Also, run() function in Thread class calls  To create the thread, the next step is to create some objects (two in this example) of our thread-supported class. We call the start method of each object – this in turn executes the run method of each object. # Run following code when the program starts. if __name__ == '__main__': # Declare objects of MyThread class. myThreadOb1 = MyThread(4)

Python : How to Create a Thread to run a function in parallel , For that new need to create a Thread class object and pass function name (which we want to execute in new thread) in target argument i.e.. When you create a Thread, you pass it a function and a list containing the arguments to that function. In this case, you’re telling the Thread to run thread_function () and to pass it 1 as an argument. For this article, you’ll use sequential integers as names for your threads. There is threading.get_ident (), which returns a unique name for