1

When I read the documentation, it seems the lock object is mentioned in both threading and thread library, so I found there are 2 ways to create a lock: threading.Lock() and thread.allocate_lock(), and the return values are both of type thread.lock.

>>> a = thread.allocate_lock()
>>> b = threading.Lock()
>>> a
<thread.lock object at 0x1002ab190>
>>> b
<thread.lock object at 0x1002ab0f0>

I wonder if there's any difference between these 2 creation methods?

1 Answer 1

2

Python Docs itself recommends the threading module.

Note
The thread module has been renamed to _thread in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0; however, you should consider using the high-level threading module instead.

The threading module lays on top of the thread module, as stated in the threading docs

This module constructs higher-level threading interfaces on top of the lower level thread module. See also the mutex and Queue modules.

So one would assume that the locks they use are very close to identical, but the threading module wraps the thread modules calls.

Indeed later in the threading docs, it states:

A primitive lock is a synchronization primitive that is not owned by a particular thread when locked. In Python, it is currently the lowest level synchronization primitive available, implemented directly by the thread extension module.

So in summary, they are most likely identical, and python itself recommends the threading module. So use that if you are in doubt.

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.