How can I invoke a thread multiple times in Python?

2024/9/29 21:23:46

I'm sorry if it is a stupid question. I am trying to use a number of classes of multi-threading to finish different jobs, which involves invoking these multi-threadings at different times for many times. But I am not sure which method to use. The code looks like this:

class workers1(Thread):  def __init__(self):  Thread.__init__(self)  def run(self):  do some stuff  class workers2(Thread):  def __init__(self):  Thread.__init__(self)  def run(self):  do some stuff  class workers3(Thread):  def __init__(self):  Thread.__init__(self)  def run(self):do some stuff  WorkerList1=[workers1(i) for i in range(X)]  
WorkerList2=[workers2(i) for i in range(XX)]  
WorkerList2=[workers3(i) for i in range(XXX)]  while True:  for thread in WorkerList1:  thread.run (start? join? or?)for thread in WorkerList2:  thread.run (start? join? or?)  for thread in WorkerList3:  thread.run (start? join? or?)  do sth  .

I am trying to have all the threads in all the WorkerList to start functioning at the same time, or at least start around the same time. After sometime once they were all terminated, I would like to invoke all the threads again.

If there were no loop, I can just use .start; but since I can only start a thread once, start apparently does not fit here. If I use run, it seems that all the threads start sequentially, not only the threads in the same list, but also threads from different lists.

Can anyone please help?

Answer

there are a lot of misconceptions here:

  • you can only start a specific instance of a thread once. but in your case, the for loop is looping over different instances of a thread, each instance being assigned to the variable thread in the loop, so there is no problem at all in calling the start() method over each thread. (you can think of it as if the variable thread is an alias of the Thread() object instantiated in your list)

  • run() is not the same as join(): calling run() performs as if you were programming sequentially. the run() method does not start a new thread, it simply execute the statements in in the method, as for any other function call.

  • join() does not start executing anything: it only waits for a thread to finish. in order for join() to work properly for a thread, you have to call start() on this thread first.

additionally, you should note that you cannot restart a thread once it has finished execution: you have to recreate the thread object for it to be started again. one workaround to get this working is to call Thread.__init__() at the end of the run() method. however, i would not recommend doing this since this will disallow the use of the join() method to detect the end of execution of the thread.

https://en.xdnf.cn/q/71162.html

Related Q&A

Matplotlib interactive graph embedded in PyQt

Ive created a simple python script that when run should display an embedded matplotlib graph inside a PyQT window. Ive used this tutorial for embedding and running the graph. Aside from some difference…

How to pass path names to Python script by dropping files/folders over script icon

I am working in Mac OS X and have been writing simple file/folder copy scripts in Python. Is there a way to drag and drop a folder on top of a Python script icon and pass the file or folders path as an…

Why wouldnt I want to add Python.exe to my System Path at install time?

Im reinstalling Python, on Windows 7, and one of the first dialog boxes is the Customize Python screen.The default setting for "Add Python.exe to Path" is "Entire feature will be unavail…

How to install python-gtk2, python-webkit and python-jswebkit on OSX

Ive read through many of the related questions but am still unclear how to do this as there are many software combinations available and many solutions seem outdated.What is the best way to install the…

Forking python, defunct child

I have some troubles with Python child processes so I wrote a very simple script:import os import sys import timepid = os.fork() if pid:#parenttime.sleep(30) else:#child#os._exit(0)sys.exit()While pare…

is there a way to know the length of a bytearray variable in python?

I have this code:variable = "FFFF" message = bytearray( variable.decode("hex") )after this, I want to perform something like this:message.len()but it seems that bytearray does not h…

Matplotlib: Check for empty plot

I have a loop which loads and plots some data, something like this:import os import numpy as np import matplotlib.pyplot as pltfor filename in filenames:plt.figure()if os.path.exists(filename):x, y = n…

Hyperlink in Streamlit dataframe

I am attempting to display a clickable hyperlink inside a dataframe containing filtered results on Streamlit. This is my code so far: import pandas as pd import streamlit as st import openpyxl import n…

Best way to detect if checkbox is ticked

My work:Scan the paper Check horizontal and vertical line Detect checkbox How to know checkbox is ticked or notAt this point, I thought I could find it by using Hierarchical and Contours: Below is my w…

ResultSet object has no attribute find_all

i always met one problem, when I scraping one web page.AttributeError: ResultSet object has no attribute find. Youre probably treating a list of items like a single item. Did you call find_all() when y…