Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23247

Lock classes and Threading in python for dict moifications

$
0
0

I was learning and testing threading in python, and Lock class, So in here I want to add a key to persons but let's say it will takes some time, in another thread I want to read the key. in first thread I should lock the process but I still get error

import threadingfrom time import sleeppersons = {"test": "test","test2": "test2",}lock = threading.Lock()def func1():    global persons    lock.acquire()    sleep(10)    persons["test3"] = "test3"    lock.release()def func2():    global persons    print(persons["test3"])t1 = threading.Thread(target=func1)t2 = threading.Thread(target=func2)t1.start()t2.start()t2.join()t1.join()

I lock the func1() but still get error

KeyError: 'test3'

can anyone help me what I miss understand here, the func1 should have lock the persons but it's not.


Viewing all articles
Browse latest Browse all 23247

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>