17

I started studying python a couple of month ago, then I found Jython.

Do threads work properly in Jython, since it doesn't have a GIL? If so, can you suggest a good book on concurrency (threading)?

Community
  • 1
  • 1
nassio
  • 635
  • 1
  • 10
  • 19
  • 3
    This is a good question, I honestly don't know the answer but I have multithreaded with both so maybe a better question is: `Do I need to use python multiprocessing or Java's threading`? I'm sure it works just not sure which one you have to use since jython is a blend of both. – Lostsoul May 13 '12 at 00:04
  • Do you mean Jpython, or Jython? This is the type of open-ended question that's not really a good fit for SO, btw. – Joel Cornett May 13 '12 at 00:06
  • According to [this question(http://stackoverflow.com/questions/4227269/hidden-multithreading-bottlenecks-in-jython), the answer is yes. I understand that it is possible to access either the python multithreading libraries, or the java concurrency support through jython. – Joel Cornett May 13 '12 at 00:12
  • I edited the question, I meant jython, sorry – nassio May 13 '12 at 00:13
  • @Lostsoul, no I don't want to use python multiprocessing, since I don't need process but I need threads, thank you anyway – nassio May 13 '12 at 00:15
  • @nassio I could be wrong, but I thought python didn't do threading because of the GIL and instead could only multiprocess. – Lostsoul May 13 '12 at 00:16
  • What I would like to achieve is parallelism, using threads and since the GIL I can't using Cpython – nassio May 13 '12 at 00:17
  • @nassio: jython does not have the GIL. – Joel Cornett May 13 '12 at 00:19
  • @Lostsoul, python does multithreading however it isn't "real" since the GIL make the run one by one, therefore you don't actually achieve "true" parallelism(at least that's what I understood). – nassio May 13 '12 at 00:19
  • @JoelCornett thanks, do you perhaps know any good book or any kind of tutorial, resource with focus on threading, or at least more then a simple example? – nassio May 13 '12 at 00:21
  • 1
    @Lostsoul (and nassio) When talking about different python dialects, it's a pretty good idea to be specific and use `cpython` for the usual c version. The GIL is only a limitation of that one (admittedly dominant) dialect. Real concurrent threads work just fine under Jython, IronPython and so on (though as far as I know not a single one of them specifies their exact memory model, so that's problematic. I wouldn't want to presume the memory model of the host platform holds for the interpreter) – Voo May 13 '12 at 00:32
  • @nassio: Unfortunately, I do not. What's wrong with [multiprocessing](http://stackoverflow.com/questions/3044580/multiprocessing-vs-threading-python), by the way? – Joel Cornett May 13 '12 at 00:32
  • @JoelCornett, there is nothing wrong with the multiprocessing itself, I just don't need process, simply because of the difference between treads and processes(memory footprint, expensive to fire up etc). – nassio May 13 '12 at 00:41
  • @Voo, you are right I should refer to it by using cpython(istead of only python), and btw why do you think that is gonna be problematic? – nassio May 13 '12 at 00:44
  • @nassio Do you mean the non specified memory model? Well without a memory model you can't write *any* reliable multithreaded program where threads interact in any way. Take Jython for example: Does synchronization of a method also guarantee a memory barrier? Python itself doesn't say, so the Jython guys don't have to. They could though and realistically they will (because they are probably using java constructs and the Java memory model is clear on that point), but now you're relying on implementation details. – Voo May 13 '12 at 00:48
  • cont. Ask the c/c++ guys about how much fun it is to write multithreaded programs that only reliably work on one specific OS with one specific compiler version ;) Imho one of the biggest pluses of java was the specific memory model (which is far from perfect to be clear) – Voo May 13 '12 at 00:49
  • @Voo thanks I think I got your point... btw now I'll try to use treads as they are in cpython but using jython and I'll see what's gonna happen. – nassio May 13 '12 at 01:38
  • @Voo The GIL is not only a problem with CPython. It also affects Stackless and even PyPy. Actually, every version of Python other than Jython and IronPython has a GIL, primarily because replacing it with more fine-grained mutexes impacts single-threaded performance greatly. (I'm not counting Unladen Swallow since, while it intended to remove the GIL, I'm not sure if it ever succeeded and the project is dead anyway). – Andrew Gorcester May 27 '12 at 16:00

4 Answers4

8

The best book I've encountered on multithreading is "Java Concurrency in Practice". It's very much concentrating on Java thread concurrency, and is both humbling and exciting when you start to understand the problems and the possibilities introduced by concurrency. The copy I bought a few years ago had some errata in the coding, though, which exacerbated an already brain-challenging subject: check out errata here: http://jcip.net/errata.html.

Although designed for Java developers wishing to venture into concurrency (which by the way includes anyone who's ever used a GUI interface of any kind), I'm sure the technical difficulties and subtleties outlined in the book apply to any implementation of concurrency.

By the way, I also love Jython and can confirm that anything concurrency-wise that you can do in Java you can apparently do in Jython. However, there is a caveat: concurrency can be for asynchronous programming (including GUI) and/or for performance. If for the latter you have a problem, in my opinion: Jython in my experience runs about 10 x slower than the equivalent Java program.

What this means is that your more demanding Jython modules will have to call something other than Jython for the number-crunching tasks. At the same time, Jython up to now* has not had Python's multiprocessing module, so inter-process communications are out, unless you venture into the dreaded territory of RMI. You're more of a man/woman than I if you take that option. But everything's OK: please refer to "The Definitive Guide to Jython" at http://www.jython.org ... chapter 19 is a sort of whistle-stop intro to concurrency, and chapter 10 is about integrating Java and Jython (hint: it's absurdly easy).

  • interesting: a quick glimpse at the Jython site shows that, just 10 days ago, 17/05/12, version 2.7a1 was released... an "Alpha" release. This should contain the multiprocessing module, which came in with Python 2.6. Wd be interesting to check this: if so it presumably gives you the exciting option of linking Jython and CPython processes (update later: sadly it appears for the moment that this is not so - the module name "multiprocessing" was not recognised when I tried)...

PS a final word: most experts who know much more about these things than I say that Moore's law is being superseded in importtance by Amdahl's law, which in short means that the daunting challenge of programming stable and scalable true concurrent programs will be unavoidable in the future. Exactly how easy true (i.e. thread) concurrency can be made with the use of clever code analysis tools I can't say but investment in this subject and the fascinating, intellectual new disciplines of reasoning imposed by concurrency will probably pay off... if you like a challenge.

mike rodent
  • 14,126
  • 11
  • 103
  • 157
4

Yes, with Jython you've real multi-threading. Jython (JPython successor's) is an implementation of Python that runs in the JVM. One of the main differences between Jython and the original project is that the first doesn't have the GIL and implements a real multi-threading support based on the JVM's implementation.

I'd suggest you to take a look to this book and the OReilly's one.

FlaPer87
  • 1,244
  • 9
  • 12
1

I have tried it with an example.

Requirements:
from rough import print_time
from datetime import datetime

"""
This is actually using python threading package.
One thing I came to know is that if we use the python threading module also, 
internally Jython chnages it to Java thread and work.
"""
# from threading import Thread, InterruptedException

"""
This is the java threading module.
"""
from java.lang import Thread, InterruptedException


"""
Here you can call your module from the run method.
For passing arguments, you can use the constructor of the Cycle class.
"""
class Cycle(Thread):

    def __init__(self,time1=1):
        Thread.__init__(self)
        # arguments for the run method
        self.time1 = time1

    def run(self):
        try:
            # Calling the required module with given arguments
            print_time(self.time1)
        except InterruptedException:
            print("Exception")

if __name__ == '__main__':
    print("start time:",datetime.now())
  
    for i in range(100):
        Cycle(i).start()
        
    print("end time:",datetime.now())

Please find the full code in https://github.com/om12nayak/Jython_multithreading_demo

0

The initially confusing aspect may be that you can mix and match Java and Jython's concurrency mechanisms. But it all seems to work. The reasons are:

  • Underneath Jython is the same old Java. All of its robust threading mechanisms and data structures aren't going to break even under the heavy Jython machinery.
  • Jython's threads take Java threads as their chassis and add some superstructure to make them speak the Python threading API. (There is no better way to make porting threaded Python code easier.) But the essence of the two types of threads is similar. Except that with Jython threads

    ... there are no priorities, no thread groups, and threads cannot be destroyed, stopped, suspended, resumed, or interrupted. [1]

The Python idioms are probably a bit more convenient, because, for example, if you wish to do the equivalent of synchronized (some_object) { ... }, there is a small bit of fiddling required, which is likely to be less readable than using an RLock.

Evgeni Sergeev
  • 22,495
  • 17
  • 107
  • 124