I'm a doctorate candidate working at Institute of Water Quality Control, Garching, Germany. More Info...
29 Dec 2009 |
|
If you have a serial code or software, i.e. a Matlab .m file, and a 8 core workstation laying in your lab, I bet you are already looking for a method to speed up your work. Here, I show you how to use threading in Python as an easy alternative to other methods such as Nvidia's CUDA. Let's get started. Let's say you have 250x8 jobs to be done. This can be to segment a series of TIFF images. By implementing simple threading, you can have a loop over 8 cores and apply it 250 times.This method has a problem: it is not flexible and robust enough for scientific computing (or online data extraction). What if one of the threads keeps waiting for the response, or your loop can not be applied over a definite number of repeats? Instead, I will use Queue to get over the problems mentioned above. Queue will have a pool of worker threads and assign tasks to them once finished the task before. Something like a 5 worker team with 2000 boxes to put in a truck. Once a box is put inside the truck, the next box is given to the worker to carry inside. Problem definition: We have 120 TIFF images, which each image has 250 slices inside. You want to apply a simple filter to each slice. Next, we will initiate some variables: Then, we initilize some worker threads and let them wait for jobs to accept. We start the outer loop for 120 images Then inside the outer loop, we go over slices in each image and tell Queue to put a job into the list and then apply the filter function. You send the name of the file and slice to the function as highlighted below: Now, the function that will do the calculations: The order of the python code is first the variable definition, then the worker function and finally the thread initiation and loops over the images. Here is the complete python file. Enjoy. |
Comments
interesting for everyone
your last exemple, the most useful, is just unreadable.
If you go over the code, there is a little javascript that pops up, with something like this:
That is the source code, and is formatted.
If it doesn't work, let me know ;)
Quoting amazigh
RSS feed for comments to this post