问题
If a software project supports a version of Python that multiprocessing has been backported to, is there any reason to use threading.Lock
over multiprocessing.Lock
? Would a multiprocessing
lock not be thread safe as well?
For that matter, is there a reason to use any synchronization primitives from threading
that are also in multiprocessing
?
回答1:
The threading module's synchronization primitive are lighter and faster than multiprocessing, due to the lack of dealing with shared semaphores, etc. If you are using threads; use threading's locks. Processes should use multiprocessing's locks.
回答2:
I would expect the multi-threading synchronization primitives to be quite faster as they can use shared memory area easily. But I suppose you will have to perform speed test to be sure of it. Also, you might have side-effects that are quite unwanted (and unspecified in the doc).
For example, a process-wise lock could very well block all threads of the process. And if it doesn't, releasing a lock might not wake up the threads of the process.
In short, if you want your code to work for sure, you should use the thread-synchronization primitives if you are using threads and the process-synchronization primitives if you are using processes. Otherwise, it might work on your platform only, or even just with your specific version of Python.
回答3:
multiprocessing
and threading
packages have slightly different aims, though both are concurrency related. threading
coordinates threads within one process, while multiprocessing
provide thread-like interface for coordinating multiple processes.
If your application doesn't spawn new processes which require data synchronization, multiprocessing
is a bit more heavy weight, and threading
package should be better suited.
来源:https://stackoverflow.com/questions/1980479/is-there-any-reason-to-use-threading-lock-over-multiprocessing-lock