1

Is there a way that I can have a single variable across active threads like below

count = 0
threadA(count)
threadB(count)

threadA(count):
    #do stuff
    count += 1
threadB(count):
    #do stuff
    print count

so that count will print out 1? I changed the variable in thread A and it reflected across to the other thread?

2
  • I'll assume you've left out the actual thread creation for conciseness, but it would seem the biggest problem here is that you are hiding the global variable with a parameter of your functions. That is, threadA modifies its parameter and not the global. Commented Jul 12, 2014 at 21:31
  • Hmm yes that is it. so if i do not pass count in as a parameter than when i add the 1 to count in threadA count will then be 1 and then when it prints inside threadB it will print 1? whereas if i pass it in the scope changes to just the thread? Commented Jul 12, 2014 at 21:37

2 Answers 2

1

Your variable count is already available to all your threads. But you need to synchronize access to it, or you will lose updates. Look into using a lock to protect access to the count.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok thank you, I am just reading about multithreading with the Thread Module so Ill keep that in mind.
0

If you want to use processes instead of threads, use multiprocessing. It has more features, including having a Manager objects which handles shared objects for you. As a perk, you can share objects across machines!

source

import multiprocessing, signal, time

def producer(objlist):
    '''
    add an item to list every sec
    '''
    while True:
        try:
            time.sleep(1)
        except KeyboardInterrupt:
            return
        msg = 'ding: {:04d}'.format(int(time.time()) % 10000)
        objlist.append( msg )
        print msg


def scanner(objlist):
    '''
    every now and then, consume objlist & run calculation
    '''
    while True:
        try:
            time.sleep(3)
        except KeyboardInterrupt:
            return
        print 'items: {}'.format( list(objlist) )
        objlist[:] = []


def main():

    # create obj sharable between all processes
    manager = multiprocessing.Manager()
    my_objlist = manager.list() # pylint: disable=E1101

    multiprocessing.Process(
        target=producer, args=(my_objlist,),
    ).start()

    multiprocessing.Process(
        target=scanner, args=(my_objlist,),
    ).start()

    # kill everything after a few seconds
    signal.signal(
        signal.SIGALRM, 
        lambda _sig,_frame: manager.shutdown(),
        )
    signal.alarm(12)

    try:
        manager.join() # wait until both workers die
    except KeyboardInterrupt:
        pass


if __name__=='__main__':
    main()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.