简体   繁体   English

Python - 在非线程中锁定全局变量

[英]Python - lock global variable in not thread

I have global variable that I'd like to access from thread and from main program:我有我想从线程和主程序访问的全局变量:

import thread
var = 0
def abc(lock):
    lock.acquire()
    var = 1
    lock.release()
lock = thread.allocate_lock()
thread.start_new_thread(abc, (lock))
while True:
    #should I put lock.acquire() here?
    var = 2
    #and should I put lock.realease() here?

I would imagine something like this.我会想象这样的事情。 At least I do it that way with only threads (by the way - is it OK to pass lock into thread like that? I do that with all of them).至少我只用线程这样做(顺便说一下 - 可以像那样将锁传递给线程吗?我对所有线程都这样做)。 If it is not possible the only way is to put main code into thread too?如果不可能,唯一的方法是将主代码也放入线程中吗?

Since there is GIL(Global Interpretation Lock) you can use a global variable to pass data between threads.由于有 GIL(全局解释锁),您可以使用全局变量在线程之间传递数据。 Since threads shares the same memory and you cannot deadlock the application, you can safely use a global variable or pass the variable as an argument when thread is first created.由于线程共享相同的 memory 并且您不能死锁应用程序,因此您可以安全地使用全局变量或在首次创建线程时将变量作为参数传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM