0

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?

Ri Di
  • 163
  • 5
  • I know you're really asking about a `mutex`, but the way to pass data between Python threads is through a `Queue` and that makes your question a duplicate of https://stackoverflow.com/questions/25904537/how-do-i-send-data-to-a-running-python-thread – Grismar Aug 11 '20 at 07:24
  • Does this answer your question? [How do I send data to a running python thread?](https://stackoverflow.com/questions/25904537/how-do-i-send-data-to-a-running-python-thread) – Grismar Aug 11 '20 at 07:24
  • well, as I understand this solution sends data to thread. I need to get it from thread. I was thinking to use global variables as I shown. So is it possible? – Ri Di Aug 11 '20 at 07:36

1 Answers1

0

Since there is GIL(Global Interpretation Lock) you can use a global variable to pass data between threads. 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.