A
A
Alexey Yarkov2016-01-18 17:05:03
Python
Alexey Yarkov, 2016-01-18 17:05:03

Will I ever understand threads in Python?

We have the following test code:

import threading
import random

lock = threading.BoundedSemaphore(value=5)

def write(*args, **kwargs):
    global lock
    lock.acquire()
    print "Thread name: %s. Result %-6f" % (args)
    lock.release()

class App(threading.Thread):
    
    def __init__(self, *args, **kwargs):
        threading.Thread.__init__(self, *args, **kwargs)
    
    def run(self):
        for i in xrange(5000):
            r = random.random()
            i = i*i-789*96/2*r
        write(self.name, i)
 
for i in xrange(5):
    app = App(name="THREADING_%d" % (i))
    app.start()

Well, everything is fine, but the feeling that the locks do not work. The screenshot shows that the lines in the console get uneven. It should be?
b2b3ce989aa14ee7b3f70f3f5bcb762e.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Yarkov, 2016-01-18
@yarkov

And here is what you need:

import threading
import random

lock = threading.RLock() # <<< one

def write(*args, **kwargs):
    global lock
    with lock: # <<< two
        print "Thread name: %s. Result %-6f" % (args)

class App(threading.Thread):
    
    def __init__(self, *args, **kwargs):
        threading.Thread.__init__(self, *args, **kwargs)
        self.setDaemon(False)
    
    def run(self):
        for i in xrange(5000):
            r = random.random()
            i = i*i-789*96/2*r
        write(self.name, i)
        


for i in xrange(5):
    app = App(name="THREADING_%d" % (i))
    app.start()

V
Vladimir, 2016-01-18
@vintello

Yes, it is normal

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question