multithreading - Python creating a shared variable between threads -


i'm working on project in python using "thread" module.

how can make global variable (in case need true or false) threads in project (about 4-6) can access?

we can define variable outside thread classes , declare global inside methods of classes.

please see below trivial example prints ab alternatively. 2 variables 'flag' , 'val' shared between 2 threads thread_a , thread_b. thread_a prints val=20 , sets val 30. thread_b prints val=30 since val modified in thread_a. thread_b sets val 20 again used in thread_a. demonstrates variable 'val' shared between 2 threads. variable 'flag' shared between 2 threads.

import threading import time c = threading.condition() flag = 0      #shared between thread_a , thread_b val = 20  class thread_a(threading.thread):     def __init__(self, name):         threading.thread.__init__(self)         self.name = name      def run(self):         global flag         global val     #made global here         while true:             c.acquire()             if flag == 0:                 print "a: val=" + str(val)                 time.sleep(0.1)                 flag = 1                 val = 30                 c.notify_all()             else:                 c.wait()             c.release()   class thread_b(threading.thread):     def __init__(self, name):         threading.thread.__init__(self)         self.name = name      def run(self):         global flag         global val    #made global here         while true:             c.acquire()             if flag == 1:                 print "b: val=" + str(val)                 time.sleep(0.5)                 flag = 0                 val = 20                 c.notify_all()             else:                 c.wait()             c.release()   = thread_a("mythread_name_a") b = thread_b("mythread_name_b")  b.start() a.start()  a.join() b.join() 

output looks like

a: val=20 b: val=30 a: val=20 b: val=30 a: val=20 b: val=30 a: val=20 b: val=30 

each thread prints value modified in thread.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -