Python Threading: Multiple While True loops

2024/10/11 8:24:21

Do you guys have any recommendations on what python modules to use for the following application: I would like to create a daemon which runs 2 threads, both with while True: loops.

Any examples would be greatly appreciated! Thanks in advance.

Update: Here is what I have come up with, but the behavior is not what I expected.

import time
import threadingclass AddDaemon(object):def __init__(self):self.stuff = 'hi there this is AddDaemon'def add(self):while True:print self.stufftime.sleep(5)class RemoveDaemon(object):def __init__(self):self.stuff = 'hi this is RemoveDaemon'def rem(self):while True:print self.stufftime.sleep(1)def run():a = AddDaemon()r = RemoveDaemon()t1 = threading.Thread(target=r.rem())t2 = threading.Thread(target=a.add())t1.setDaemon(True)t2.setDaemon(True)t1.start()t2.start()while True:passrun()

output

Connected to pydev debugger (build 163.10154.50)
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon

It looks like when I try to create a thread object using:

t1 = threading.Thread(target=r.rem())
t2 = threading.Thread(target=a.add())

the while loop in r.rem() is the only one that gets executed. What am I doing wrong?

Answer

When you are creating your threads t1 and t2, you need to pass the function not call it. when you call r.rem(), it enters the infinite loop before you create the thread and separate it from the main one. the solution to this is to remove the parenthesis from r.rem() and a.add() in your thread constructors.

import time
import threadingclass AddDaemon(object):def __init__(self):self.stuff = 'hi there this is AddDaemon'def add(self):while True:print(self.stuff)time.sleep(3)class RemoveDaemon(object):def __init__(self):self.stuff = 'hi this is RemoveDaemon'def rem(self):while True:print(self.stuff)time.sleep(1)def main():a = AddDaemon()r = RemoveDaemon()t1 = threading.Thread(target=r.rem)t2 = threading.Thread(target=a.add)t1.setDaemon(True)t2.setDaemon(True)t1.start()t2.start()time.sleep(10)if __name__ == '__main__':main()
https://en.xdnf.cn/q/69795.html

Related Q&A

Visual Studio Code - input function in Python

I am trying out Visual Studio Code, to learn Python.I am writing a starter piece of code to just take an input from the user, say:S = input("Whats your name? ")When I try to run this (Mac: C…

DRF: how to change the value of the model fields before saving to the database

If I need to change some field values before saving to the database as I think models method clear() is suitable. But I cant call him despite all my efforts.For example fields email I need set to lowe…

keep matplotlib / pyplot windows open after code termination

Id like python to make a plot, display it without blocking the control flow, and leave the plot open after the code exits. Is this possible?This, and related subjects exist (see below) in numerous ot…

socket python : recvfrom

I would like to know if socket.recvfrom in python is a blocking function ? I couldnt find my answer in the documentation If it isnt, what will be return if nothing is receive ? An empty string ? In…

pandas read_excel(sheet name = None) returns a dictionary of strings, not dataframes?

The pandas read_excel documentation says that specifying sheet_name = None should return "All sheets as a dictionary of DataFrames". However when I try to use it like so I get a dictionary of…

Plotly: How to assign specific colors for categories? [duplicate]

This question already has an answer here:How to define colors in a figure using Plotly Graph Objects and Plotly Express(1 answer)Closed 2 years ago.I have a pandas dataframe of electricity generation m…

Using nested asyncio.gather() inside another asyncio.gather()

I have a class with various methods. I have a method in that class something like :class MyClass:async def master_method(self):tasks = [self.sub_method() for _ in range(10)]results = await asyncio.gath…

AttributeError: type object Word2Vec has no attribute load_word2vec_format

I am trying to implement word2vec model and getting Attribute error AttributeError: type object Word2Vec has no attribute load_word2vec_formatBelow is the code :wv = Word2Vec.load_word2vec_format("…

Python - Core Speed [duplicate]

This question already has answers here:Getting processor information in Python(12 answers)Closed 8 years ago.Im trying to find out where this value is stored in both windows and osx, in order to do som…

App Engine, transactions, and idempotency

Please help me find my misunderstanding.I am writing an RPG on App Engine. Certain actions the player takes consume a certain stat. If the stat reaches zero the player can take no more actions. I start…