threads

Z

Zunbeltz Izaola

Hi

I have create two threads (from threading module). I want to
synchronize this two in the folowwing way

def Threa1func():
do stuff..
while something
if test:
CHANGE TO Thread2
do stuff...

def Thread2func():
do stuff ...
CHANGE TO Thread1

Thread1 = threading.Thread(target=Thread1func)
Thread2 = threading.Thread(target=Thread2func)

them i've started this two threads

Thread1.start()
Thread2.start()

I want to know if it is posible to do this CHANGE of threads.

thanks in advance

Zunbeltz
 
P

Peter Hansen

Zunbeltz said:
I have create two threads (from threading module). I want to
synchronize this two in the folowwing way

def Threa1func():
do stuff..
while something
if test:
CHANGE TO Thread2
do stuff...

def Thread2func():
do stuff ...
CHANGE TO Thread1

Thread1 = threading.Thread(target=Thread1func)
Thread2 = threading.Thread(target=Thread2func)

them i've started this two threads

Thread1.start()
Thread2.start()

I want to know if it is posible to do this CHANGE of threads.

Not exactly, or yes, depending on what you really want to do.

Can you describe the problem in different terms, without reference
to actual Python code or the threading module? It's not at all clear
that you really want to use threads for your problem, and if you
do, you are looking for a different concept than "CHANGE"... maybe
semaphores or something.

-Peter
 
A

Alan Kennedy

[Zunbeltz Izaola]
I want to know if it is posible to do this CHANGE of threads.

It is not possible to "switch" execution between threads like this:
the whole point of threads is that there multiple execution contexts
operating in parallel.

Once a thread has been started, it must run all the way through until
it's execution terminates naturally. You cannot even raise exceptions
in one thread from another thread.

What you *can* do is communicate information between threads. This is
most often done by using a Queue object, which you can read about here

http://www.python.org/doc/current/lib/module-Queue.html

So a good design pattern for what (I think) you're trying to do is to
devise a class/object which represents the work to be done, and send
that "work object" back and forth on the Queue between the threads.
This way, it "appears" that the work is actually moving between
threads. When there is no work for a thread to do, it is blocked in a
Queue.get call, waiting for something to do. But it does not "go
away".

Of course, this is just one way to do it: another poster suggested
another excellent approach: co-routines.

HTH,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,920
Members
47,464
Latest member
Bobbylenly

Latest Threads

Top