473,666 Members | 2,539 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

threading priority

Hi, Is there any way to increase/decrease a thread priority in Python?

Best regards,

-- Wong

Jul 18 '05 #1
4 4897
Joe Wong wrote:
Hi, Is there any way to increase/decrease a thread priority in Python?


Not really, and as Python does not use a "free-threading" model,
it wouldn't work as you'd like anyway.

Search Google for "Python GIL" or "Global Interpreter Lock" and you
should learn enough to see why this is so.

-Peter
Jul 18 '05 #2
I googled as suggested, and the answer isn't crystal clear. My
impression is that the problem is that a python thread must acquire the
GIL in order to execute, and the strategy for deciding which thread
should get the GIL when multiple threads are waiting for it is not
based on priority. Is that correct?

-Alec
Peter Hansen wrote:
Joe Wong wrote:
Hi, Is there any way to increase/decrease a thread priority in
Python?
Not really, and as Python does not use a "free-threading" model,
it wouldn't work as you'd like anyway.

Search Google for "Python GIL" or "Global Interpreter Lock" and you
should learn enough to see why this is so.

-Peter


Jul 18 '05 #3
al****@gmail.co m wrote:
I googled as suggested, and the answer isn't crystal clear. My
impression is that the problem is that a python thread must acquire the
GIL in order to execute, and the strategy for deciding which thread
should get the GIL when multiple threads are waiting for it is not
based on priority. Is that correct?


That's basically correct. I don't actually know what
the strategy is, though I suspect it's either not
formally documented or explicitly not defined, though
for a given platform there may be some non-arbitrary
pattern...

Think of it this way: you have threads to which you have
given different priorities (somehow, using a platform-dependent
technique). The high priority thread runs first (for the
sake of this example only) in the interpreter, executes
a number of bytecode instructions equal to sys.getcheckint erval()
(miraculously without calling any extension modules or
blocking in any other way, again for the sake of this
example), and then has the GIL taken away from it by
the interpreter, thus blocking the thread. The interpreter
then gives the GIL to the lower priority thread (because
it isn't aware of the priorities assigned to the native
thread) and *it* runs for sys.getcheckint erval()
bytecode instructions, which might be a rather long
time. You have effectively no way to force the higher
priority thread to get the CPU whenever it is ready to
run, so long as the lower priority thread is also ready
to run. In effect, Python doesn't see the priorities at
all, and it is in almost sole control of which thread
runs when.

Or something like that. I'll rapidly be corrected if
I'm fundamentally wrong (and maybe even if I'm not ;-).

-Peter
Jul 18 '05 #4
Peter Hansen <pe***@engcorp. com> writes:
al****@gmail.co m wrote:
I googled as suggested, and the answer isn't crystal clear. My
impression is that the problem is that a python thread must acquire the
GIL in order to execute, and the strategy for deciding which thread
should get the GIL when multiple threads are waiting for it is not
based on priority. Is that correct?


That's basically correct. I don't actually know what
the strategy is, though I suspect it's either not
formally documented or explicitly not defined, though
for a given platform there may be some non-arbitrary
pattern...
(...)


I expect the Python interpreter has little to say over thread
prioritization and choice of execution, although it does impose some
granularity on the rate of switching. The GIL itself is implemented
on the lower layer lock implementation, which is taken from the native
threading implementation for the platform.

Therefore, when multiple Python threads are waiting for the GIL, which
one is going to get released will depend on when the underlying OS
satisfies the lock request from the threads, which should be based on
the OS thread scheduling system and have nothing to do with Python
per-se.

I do believe you are correct in that the Python GIL prevents thread
pre-emption by the OS (because all other Python threads are waiting on
the GIL and not in a running state), but the actual act of switching
threads at a switching point (sys.setcheckin terval()) would be an OS
only decision, and subject to whatever standard platform thread
scheduling rules were in place.

So if you were to use a platform specific method to control thread
priority, that method should be honored by the Python threads (subject
to the granularity of the system check interval for context switches).
For example, here's a Windows approach that fiddles with the thread
priority:

- - - - - - - - - - - - - - - - - - - - - - - - -
import threading
import ctypes
import time

w32 = ctypes.windll.k ernel32

THREAD_SET_INFO RMATION = 0x20
THREAD_PRIORITY _ABOVE_NORMAL = 1

class DummyThread(thr eading.Thread):

def __init__(self, begin, name, iterations):
threading.Threa d.__init__(self )
self.begin = begin
self.tid = None
self.iterations = iterations
self.setName(na me)

def setPriority(sel f, priority):
if not self.isAlive():
print 'Unable to set priority of stopped thread'

handle = w32.OpenThread( THREAD_SET_INFO RMATION, False, self.tid)
result = w32.SetThreadPr iority(handle, priority)
w32.CloseHandle (handle)
if not result:
print 'Failed to set priority of thread', w32.GetLastErro r()

def run(self):
self.tid = w32.GetCurrentT hreadId()
name = self.getName()

self.begin.wait ()
while self.iterations :
print name, 'running'
start = time.time()
while time.time() - start < 1:
pass
self.iterations -= 1
if __name__ == "__main__":

start = threading.Event ()

normal = DummyThread(sta rt, 'normal', 10)
high = DummyThread(sta rt, 'high', 10)

normal.start()
high.start()

# XXX - This line adjusts priority - XXX
high.setPriorit y(THREAD_PRIORI TY_ABOVE_NORMAL )

# Trigger thread execution
start.set()
- - - - - - - - - - - - - - - - - - - - - - - - -

And the results of running this with and without the setPriority call:

Without: With:

normal running high running
high running high running
normal running high running
high running high running
normal running normal running
high running high running
normal running high running
high running high running
normal running high running
high running normal running
normal running high running
high running high running
normal running normal running
high running normal running
normal running normal running
high running normal running
normal running normal running
high running normal running
normal running normal running
high running normal running
I'm not entirely positive why the normal thread gets occasionally
executed before the high thread is done. It might be that the
interpreter is actually releasing the GIL in the code I've written for
the thread's run() (maybe during the I/O) which opens up an
opportunity, or it may be that Windows is boosting the other thread
occasionally to avoid starvation. So I expect the normal thread is
getting occasional bursts of bytecode execution (the syscheckinterva l).

But clearly the OS level prioritization is largely driving things.

-- David
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
6472
by: Jane Austine | last post by:
As far as I know python's threading module models after Java's. However, I can't find something equivalent to Java's interrupt and isInterrupted methods, along with InterruptedException. "somethread.interrupt()" will wake somethread up when it's in sleeping/waiting state. Is there any way of doing this with python's thread? I suppose thread interrupt is a very primitive functionality for stopping a blocked thread.
77
5262
by: Jon Skeet [C# MVP] | last post by:
Please excuse the cross-post - I'm pretty sure I've had interest in the article on all the groups this is posted to. I've finally managed to finish my article on multi-threading - at least for the moment. I'd be *very* grateful if people with any interest in multi-threading would read it (even just bits of it - it's somewhat long to go through the whole thing!) to check for accuracy, effectiveness of examples, etc. Feel free to mail...
4
4086
by: Bardo | last post by:
Hi, I have a situation where I am capturing both a WMI event utilising the "ManagementEventWatcher" in the "System.Management" namespace, and a corresponding event ("EntryWritten") raised from the "EventLog" object in the "System.Diagnostics" namespace. When a certain event occurrs, both a WMI event is raised, and an event log entry is written. The problem I have is that I need to capture both events and somehow correlate which WMI...
1
2098
by: craigedmunds | last post by:
Was having a few problems with some threading issues following the microsoft support webcast Microsoft ASP.NET Threading. Spoke to Wade Mascia & managed to get clarification. Thought i'd share it with you... From: Wade Mascia Hi Craig As for resources, keep an eye out for a book we're working on. So far it's just code named (PerfNScale), but it will probably come out with a name like "Improving Distributed Application Performance"....
7
3227
by: IcedCrow | last post by:
I have code: Dim th as new threading.thread(addressof MyMethod) th.start() If th.threadstate = threadstate.running then th.priority = threading.threadpriority.abovenormal End If My question is... wouldn't the thread always be running and the if statement always fire off with setting the
9
1746
by: AdrianJMartin | last post by:
Hi all, I have a need for a STA thread from asp.net. I can create the thread and it runs fine. But when it is finished, the thread still 'hangs' arround. Visible only to the debugger..... I get the "The thread has exited with code 0 (0x12fc)." in the debugger each time the thread seemly end, but its still there in the thread window. GC.Collect() does not get rid of them either, something must be holding a reference to the...
4
1607
by: Lee Moore | last post by:
I am trying to develop a threaded function to create a dataset from an Oracle database. When querying an elaborate view, queries take a while. I would like to place and animated wait dialog up while the query runs. I don't know much about threading, so bear with me. The following code contains a class that works fine when threading is not used, but fails to return a dataset when I execute the threading code. Any help would be appreciated....
8
2442
by: Luc | last post by:
Hi, I am writing software to automate some testing. I have one main form to set up the tests, and once this is complete, I open 4 identical forms to monitor each different device that I am automating. Because there are many fast timers on each, I have placed each one of these forms in their own thread by using the following code: Dim NewForm As New frmFormName Dim NewThread As System.Threading.Thread NewThread = New...
8
4747
by: WhiteWizard | last post by:
I guess it's my turn to ASK a question ;) Briefly my problem: I am developing a Windows app that has several User Controls. On one of these controls, I am copying/processing some rather large binary files, so have created a second thread to do the processing. This thread is set to be the LOWEST priority. So far so good with all that. HOWEVER, I am trying to provide some feedback to the user (the bane of our existence!) via a progress...
0
8454
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8883
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8787
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8645
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6203
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4200
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2776
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1778
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.