0

I have a little threading / locking dilema. I am trying to achieve something like this:

import threading
import time

class A:

    def __init__(self):
        self.lock = threading.Lock()

    def print_stuff(self):
        with self.lock:
            ##  do some hazard with stuff !
            print("OK")

    def other_function(self):
        with self.lock:
            ## some more hazard stuff
            pass



def worker(a):
    while alive:
        """thread worker function"""
        a.print_stuff()


a = A()

alive = True
threads = []
for i in range(5):
    t = threading.Thread(target=worker, args=(a,))
    threads.append(t)
    t.start()


try:
    while True:
        pass
except KeyboardInterrupt:
    alive = False
    print('interrupted!')

There is a class A - collection of functions mainly, but with some properties also. It will be use for communication with other devices via HTTP or different protocol.

My idea is to lock every function to prevent two functions of A instance being called at the same time. To my surprise, it works without lock also, but so far I am not doing anything hazardous in the functions.

My questions:

Is the implemented lock sufficient enough to prevent any touch of the same resources by multiple threads (the workers will only call functions, they will not touch the properties of A instance)?

Is it better to make the lock global and lock the function directly in worker (instead in the A instance)? See example:

lock = threading.Lock()
def worker(a):
    while alive:
        """thread worker function"""
        with lock:
            a.print_stuff()
matousc
  • 3,698
  • 10
  • 40
  • 65
  • As an aside, `while True: pass` is very cpu intensive and slows your program because of the gil. `while True: time.sleep(1000000000)` would be better. – tdelaney Jun 05 '18 at 07:55
  • Are these workers doing any blocking? if not, then breaking them into threads and adding the lock compilcations don't help. Python's GIL only lets a single thread run at a time. See [What is a global interpreter lock (GIL)?](https://stackoverflow.com/questions/1294382/what-is-a-global-interpreter-lock-gil) for example. – tdelaney Jun 05 '18 at 08:00
  • @tdelaney The lock should allow only one thread to access the call functions - the other threads should wait for release - if they need to access in the same time. – matousc Jun 05 '18 at 08:07
  • Yes, I got that. Will they be doing anything useful outside of the lock? Threads + course grain locks tend to defeat the reason for threads in the first place. And considering that CPython only lets 1 thread run at a time anyway, unless the thread blocks somewhere, there is no performance benefit. – tdelaney Jun 05 '18 at 08:10
  • @tdelaney Yea, sorry, it was probably not clear from my post. The thing is, that the workers will do a lot of various stuff. Class A usage will be just small part of their "paralel" jobs. – matousc Jun 05 '18 at 10:21

0 Answers0