threading.Thread Need help

Official forum for open source FreePIE discussion and development.
Post Reply
PavelSokolov
One Eyed Hopeful
Posts: 2
Joined: Wed Dec 21, 2016 9:37 pm

threading.Thread Need help

Post by PavelSokolov »

Hi all.
Sorry for my English. I have a problem with the module threading.
When I use two threads, the CPU load increases significantly >50%. I usually have <2% when using FreePie without thread.
I have very little programming experience, so have absolutely no idea how to solve this problem.

Here is a sample code that I use:

Code: Select all

import threading

def myThtead():
	while True:
		if keyboard.getKeyDown(Key.Q):
			break
if starting:
	myThread_1=threading.Thread(target=myThtead,args=())
	myThread_2=threading.Thread(target=myThtead,args=())
	myThread_1.start()
	myThread_2.start()

diagnostics.watch(threading.activeCount())
any help
thank you in advance
MarijnS95
One Eyed Hopeful
Posts: 34
Joined: Tue Dec 22, 2015 12:52 pm

Re: threading.Thread Need help

Post by MarijnS95 »

Hi,

Before explaining why that happens, let me first explain how FreePIE itself works. As you probably know, the code you write in FreePIE is executed many times (approximately a 100 times) per second. This is so that it can continuously read your inputs (keyboard, mouse, joysticks etc), process the data with your code and do whatever you 'told' it to do.

Now, your CPU can go much faster than that, which is exactly what happens in your two threads; there is nothing that limits the while loop from executing as many times as possible (taking all the available CPU resources). As you have 2 threads running continuously on a 4-core CPU, this results in 50% usage.

As you found out, that's just way too much (on a dev-build of FreePIE, 4.4GHz CPU, the keyboard.getKeyDown function is called about 770.000 times a second!).
The easiest way to work around this is to "sleep" the thread. This basically tells the CPU to not execute any code from that thread for at least x seconds. If you set it to 10 miliseconds (0.01 seconds), you'll get approximately 100 executions per second.

Code: Select all

import time
# Inside the while True loop:
time.sleep(0.01) # Wait 10 miliseconds before proceeding
That said though, why are you using threads inside FreePIE in the first place? Please be aware of thread-safety (which not all FreePIE modules might be).
PavelSokolov
One Eyed Hopeful
Posts: 2
Joined: Wed Dec 21, 2016 9:37 pm

Re: threading.Thread Need help

Post by PavelSokolov »

Thank you for answering my stupid question.
Use to "sleep" really good idea.
I use threads to run macros independently of the main thread.
Post Reply

Return to “FreePIE”