1

I was wondering if there was a better way to deal with locks while importing other modules. Right now I've got this...

import ot1, ot2, ot3
class Thread(threading.Thread):
    def __init___(blah, blah):

    def run(self):
        data, my_lock = self.data, self.my_lock
        return ot1.dostuff(data, my_lock) + ot2.dostuff(data, my_lock) + ot3.dostuff(data, my_lock)
if __name__ == '__main__':
    my_lock = threading.Lock()
    for x in range(10):
        Thread(data, my_lock)

Because I'm importing things I have to pass the lock into the new areas, is there any way to work around this, like globally declare the lock. It would make my code a whole lot cleaner.

3
  • The dostuff functions access multiple data members from your thread class (data and my_lock). Would it make sense for them to be methods on the class itself? Commented Jul 16, 2015 at 0:20
  • Not in this case, it gets pretty elaborate in the background, dostuff calls other functions from other files. If I put everything one one file it will be a couple thousand lines too long. Commented Jul 16, 2015 at 0:25
  • I think it would be very interesting to know why locks are being used in the first place. Would you mind explaining your use case further? Commented Jul 16, 2015 at 0:47

1 Answer 1

1

Python has module level variables, if you really want to use them:

# main file, call it main.py
lock = None
if __name__ == '__main__':
    lock = threading.Lock()
    # launch threads without passing lock

Then, in any other file, you can do:

# other files:
from main import lock

# use the lock...

If this solves a quick problem you're dealing with, then use it. But I wouldn't really recommend it for a real programming project. It's better programming practice to have your code rely less on global state (such as module level variables), and have more explicitly passed parameters. That way you always know what your code depends on, and it's more reusable.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.