Themes in Java and Python

I have few questions about threads in Python and Java ...

  • Is it possible to set priorities for Python threads, as in Java?
  • How can I kill, stop, pause and interrupt a thread in Python?
  • Groups of topics - what are they for? Does Python support them?
  • Synchronization - in Java we just use the synchorinized keyword for a method, object ... What about Python?

Tnx!

+5
source share
6 answers

Assuming we're talking about implementing a classic (CPython):

  • no, no priorities in Python threads
  • you cannot do any of these things in a thread in python
  • no thread groups in Python
  • , , , , ( , Queue ).

, Python , Java - , Python ( C ).

- , , Python , multiprocessing - Python, , Jython JVM IronPython .NET.

+12

Java . , .

, "realtime java" (. http://www.rtsj.org), , RealtimeThread. java.lang.Thread .

+1

, :

Python, Java?

. , , . :

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

, , Python?

, . , , . . API:

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

, TerminateThread, TID. , .

- ? Python?

. .

- Java synchorinized , ... Python?

.

+1

, , ( , if-self.alive ):

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
+1

1, Java Thread , .

SCJP:

, , , .

0

Unfortunately, the standard Python package has something called a GIL, or global interpreter. This means that only one of your threads will work at a time. At the same time, simple multi-threaded applications are possible and quite easy to write. The streaming module contains basic synchronization primitives such as mutexes, sempahores, etc.

There is also a wonderful instruction manual that automates most aspects of locking. For 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"
0
source

All Articles