0

I got the following code which has the goal of running multiple while loops threaded simultaneously.
This worked for me and achieved the expected results but has the "odd" behavior of fully utilizing exactly one logical core of the cpu.
The looped functions doesn't do much other than waiting with the sleep function.

from time import sleep

sleep(60)

I can't call the functions periodically. Does someone here know why that is?

def changes(function, name):
    if function == 0:
        pass
    elif function == 1:
        print("something changed in " + str(name))
    else:
        print("something went wrong in " + str(name))




def loop_function0():
    while True:
        changes(function0(argument), "function0")

def loop_function1():
    while True:
        changes(function1(argument), "function1")





class thread0(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self.start()
    def run(self):
        loop_function0()


class thread1(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self.start()
    def run(self):
        loop_function1()


thread0()
thread1()
while True:
    pass

htop example screenshot

ammernico
  • 1
  • 1
  • Unlike threading in other languages, threading in Python will not use several cores of your CPU. Only one thread will be running at a time. Check this answer: https://stackoverflow.com/questions/31340/how-do-threads-work-in-python-and-what-are-common-python-threading-specific-pit – Santiago Peron Nov 18 '21 at 10:23
  • Thank you for the answer. Does this mean only one thread gets processed by the interpreter at a time, then the other and by switching between those two threads it creates the heavy cpu load? I'm not really concerned about multi threading since the workload should be fairly light. More about starting multiple while loops at the same time without interfering in each other. – ammernico Nov 18 '21 at 13:15
  • Would you say forking could be the answer to this? Or is threading the right way? – ammernico Nov 18 '21 at 13:18
  • At least from my experience, and from what's discussed usually within the community, threads are mostly suitable for network / IO, while processes are suitable for CPU intensive tasks. If your loops will be crunching numbers or some other CPU intensive thing, I'd say it's better if you go with processes. You can for example check multiprocessing library, maybe with a process pool, see here: https://docs.python.org/3/library/multiprocessing.html. If you want to do IO/Ntwrk tasks in parallel, from my experience, threads are a good, suitable option. – Santiago Peron Nov 22 '21 at 10:33

0 Answers0