python locking and threading concurrency [duplicate]

柔情痞子 提交于 2019-12-24 11:47:50

问题


i have a question regards python locks and threading, i realise locks are used to prevent variables from being overwritten by another thread, is it normal to use locks to get around this issue as it then means you can only run a single thread concurrently, it also means creating acquire/release locks for every variable that maybe overwritten, which for my project runs into quite a few!

how are people doing this?, wrapping the variables in thread safe lists or creating unique variables based on the thread name perhaps?, or is everybody littering their code with lock acquire and releases?.


回答1:


The best idea is to just not use threads at all. Most Python implementations have a global interpreter lock which eliminates the advantages of using threads in first place. If you're using threading to wait for IO, you can get the same or better performance if you just use asynchronous IO instead. If you're using threading to perform computation (number crunching) across processors, the python global lock prevents it from working so you're better using multiple processes instead.

In contrast with having no upside, threading in python have lots of shortcomings and caveats, like you already found out. You still have to do data sharing control, and to deal with oddities related to threads receiving cpu attention in moments you don't control. All that for no benefit.

TL;DR just don't use threads




回答2:


Please follow this link Explains various aspects of multithreading in general with Python examples



来源:https://stackoverflow.com/questions/17168883/python-locking-and-threading-concurrency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!