stdcerr
stdcerr

Reputation: 15678

Share a dictionary betweeen multiple live threads

I have a Python (2.7) application in which I run multiple threads. Now I would like to update a dictionary in my child thread and use its updated contents in my mother thread without using join(). Can I do this? I do not want to wait until my child has terminated to use the dictionary's data in my mother thread.

How can I do this?

Upvotes: 1

Views: 735

Answers (1)

Dan Gittik
Dan Gittik

Reputation: 3860

You can use the threading module or the thread module.

Here's an example using the thread module:

import thread

d = dict()
m = thread.allocate_lock()

def foo():
    m.acquire_lock()
    print(d['key'])

def bar():
    d['key'] = 'value'
    m.release_lock()

if __name__ == '__main__':

    m.acquire_lock()
    t1 = thread.start_new_thread(foo,())
    t2 = thread.start_new_thread(bar,())

This illustrates how locks can synchronize thread access to shared resources: as long as m is locked, foo is waiting to acquire it; meanwhile, bar updates the dictionary and releases the lock; only then does foo acquire the lock and continues. No joins.

(Of course, this is not how you should write multithreaded code...)

EDIT

If you have to use processes, you can find similar functionality in the multiprocessing module.

Here's an example:

import multiprocessing

def foo(m, d):
    m.acquire()
    print(d['key'])

def bar(m, d):
    d['key'] = 'value'
    m.release()

if __name__ == '__main__':

    manager = multiprocessing.Manager()

    m = multiprocessing.Lock()
    m.acquire()

    d = manager.dict()

    p1 = multiprocessing.Process(target=foo, args=(m, d))
    p2 = multiprocessing.Process(target=bar, args=(m, d))

    p1.start()
    p2.start()

The Lock allows process synchronization, and the Manager allows resource sharing for compound types like lists and dictionaries.

Upvotes: 2

Related Questions