calling functions at the same time

asdf sdf asdf at asdf.com
Fri Apr 30 22:31:59 EDT 2004


bart_nessux wrote:
> I need a script to call several functions at the same time. How does one 
> call more than one function simultaneously?
> 
> 
> 
i just added my first thread to a wxpython program today.  simple. in 
fact my first threaded program of any kind.

as indicated, threads might help you.  you didn't mention your platform 
but probably it has real thread support.  nevertheless, this might not 
be for you if you are running in a Unix environment with a 
multiprocessing (forking) program.

you launch your threads:

import thread

# create a lock you can use to block the threads until you are ready
mymutex = thread.allocate_lock()

def MyConcurrentFunction():
	# important concurrent stuff
	pass

def ThreadThing():
	# thread will hang on 'acquire' until mutex is released
	mymutex.acquire()
	# release lock for the next thread
	mymutex.release()
	# now do your stuff
	MyConcurrentFunction()

mymutex.acquire()
# launch your threads
thread.start_new_thread(ThreadThing, ())
thread.start_new_thread(ThreadThing, ())
thread.start_new_thread(ThreadThing, ())...
# your threads are all hung on the 'acquire' statement
# release the lock, unblocking the threads
mymutex.release()
# now all your threads are grabbing and releasing the mutex

# all done

I just made that whole thing up.  But i think that's more or less how 
you launch threads.

you have to consider that the thread may run as soon as you launch it. 
each thread could complete your special function before the rest of the 
threads get launched.

i think you address that problem by creating a mutex or semaphore that 
each thread must acquire before it can proceed.  That is, the thread 
will block (hang) waiting for the mutex to become available.  (think of 
a mutex as an abstract lock resource).  when all your threads are 
launched, the main program can release the mutex(es), unblocking the 
threads.  The threads will unhang, and do your concurrent thing, more or 
less concurrently.

Understand that concurrency is not guaranteed (as i understand it).  the 
   OS controls which thread runs when, and it is not deterministic.

you could use an list of mutexes, to get an iota more concurrency.

all this i learned this very day from Programming Python, pg 104. so 
take my advice with a shovel of salt.

but it sounds like the way to go to me.





More information about the Python-list mailing list