Reputation: 1042
I am writing a piece of code where I have one class A
and two threads B
and C
.
I create an instance a
of A
. I then start both threads, first B
then C
.
B
calls a function func_name
in A
by a.func_name()
. So far so fine.
C
on the other hand needs to access the result which is a list, say list_a
defined inside func_name()
in class A
and accessed by instance a
.
I have to match a set of string by using a for loop like this,
if self.string_variable in a.list_a:
print "found"
but it gives me an error:
A
instance has no attributelist_a
Can some one please help me?
Upvotes: 0
Views: 112
Reputation: 602595
You will need some kind of synchronization primitive – exactly which one depends on further details of your design and requirements.
Assuming the list a.list_b
is to be created once and is not modified later, thread C
needs to wait until a.func_name()
returns. This can be achieved by adding a threading.Event
instance to A
. In A.__init__()
, add
self.event = threading.Event()
At the end of A.func_name()
, add
self.event.set()
Before thread C
tries to access a.list_b
, add
a.event.wait()
to wait until a.func_name()
has finished in thread B
.
In general, synchronization between threads is a complex topic and an error-prone task. You should only do this if you really need to.
Upvotes: 2