views:

533

answers:

6

Hi all, i have few questions about threads in Python and Java...

  1. Is it possible to give priorities to Python threads, as it is in Java?
  2. How can I kill, stop, suspend and interrupt thread in Python?
  3. Thread groups - what are they really for? Does Python support them too?
  4. Synchronization - in Java we use simply keyword synchorinized for a method, object...What about Python?

Tnx!

+9  A: 

Assuming we're talking about the classic (CPython) implementation:

  1. no, no priorities in Python's threads
  2. you can't do any of these things to a thread in Python
  3. no thread groups in Python
  4. you can use many approaches, such as locks, but the recommended approach is generally to use the Queue module from the standard library (and limit your threads' interactions to what Queue lets you program)

In other words, Python threads are really much less rich than Java's -- not to mention that only one thread per process can in fact run Python code (others may be running C code or waiting).

For anything fancy, i.e. anything beyond Python's limited threading capabilities, it's recommended you use the multiprocessing module from the standard library -- or switch to implementations of Python that let you use richer threading approaches, such as Jython for the JVM or IronPython for .NET.

Alex Martelli
A: 

Just a sidestep about point 1 here, because Java Thread priorities might not work as one would expect.

From the SCJP guide:

Because thread-scheduling priority behaviour is not guaranteed, use thread priorities as a way to improve the efficiency of your program, but just be sure your program doesn't depend on that behaviour for correctness.

Jorn
+1  A: 

Regular java thread priorities can't be counted on. You may find a lower priority thread running when a higher priority thread is ready and waiting.

There is something called "realtime java" (see http://www.rtsj.org) which does enforce thread priority, at least for the RealtimeThread class. Regular java.lang.Thread may still not enforce true priority ordering.

JustJeff
A: 

Unfortunately the standard Python package has something called the GIL, or global interpreter lock. This means only one of your threads will ever be running at a time. That being said, simple multithreaded applications are possible and pretty easy to write. The threading module contains basic synchronization primitives like mutexes, sempahores, etc.

There is also an awesome with statement that automates most aspects of lock usages. For an example:

import threading
myLock = threading.Lock()

Then to use the lock:

with myLock:
    #lock has now been acquired
    print "I have the lock and can now to fun stuff"
print "The lock has been released"
Dan Lorenc
GIL is not **unfortunate**. With it code runs faster so it is a good thing.
nosklo
@nosklo: actually, if you have a multicore machine, the GIL makes some things slower. Check out http://us.pycon.org/2010/conference/schedule/event/P82/
yarmiganosca
@yarmiganosca: only if you write heavily-threaded code, and mix IO with cpu-intensive threads, which is not a common pattern. For most real-use cases and almost all real-life programs, the GIL is very good and improves speed.
nosklo
+1  A: 

I felt the need to debunk the common myths perpetuated here:

Is it possible to give priorities to Python threads, as it is in Java?

Not in the OS sense. But you can use cooperative multitasking and your own custom scheduler to ensure that certain threads use more time. You can also set the timeslices between a thread with this:

http://docs.python.org/library/sys.html#sys.setcheckinterval

How can I kill, stop, suspend and interrupt thread in Python?

Note that you can do it. Its just difficult, and people will wax philosophical about how it is evil. But this is true in any language. You can either use the following API function:

http://docs.python.org/c-api/init.html#PyThreadState_SetAsyncExc

Or you can use your underlying OS like TerminateThread in windows off the TID. Just be sure to acquire the global lock.

Thread groups - what are they really for? Does Python support them too?

I don't believe so. They are for controlling groups of threads.

Synchronization - in Java we use simply keyword synchorinized for a method, object...What about Python?

Read the thread and threading module.

Unknown
+1  A: 

here's an example of how I allow my threads to be halted (only works for threads within loops really, unless you wanted to place an if "self.alive" before every line):

import threading, Queue

class HaltableThread(object.Thread):
    def __init__(self):
     self.stringQueue = Queue.Queue()
     self.alive = True
    def run(self):
     while self.alive:
      try:
       data = self.stringQueue.read(0.01) #100ms block until data
      except Queue.Empty:
       pass
      else:
       print data
    def stop(self):
     self.alive = False
Sean