A simple demonstration of the threading module in Python that used both a lock and semaphore to control concurrency is by Ted Herman at the University of lowa. The code and sample output below are worth a look. Report your findings.
I download the threaddemo.py script from CSU and execute it in my PC. However, when I am executing it, it prompts out many unexpected errors. Finally, I need to downgrade the version of Python from 2.5.4 to 2.3.2. And now, i can test it in my PC successfully (see figure 1), I suspect that it may be caused by different syntax between verison 2.5.4 and 2.3.2.

Figure 1.
From the source code, I get some findings which are listing as follow:
Finding 1, thread ID is limited starting from 0 to 9.
Finding 2, variable named delay that is used to control the processing time of thread within 2 seconds.
Finding 3, variable named sema that is a threading semaphore and it is predefined running maximum 3 threads each time (sema = threading.BoundedSemaphore(value=3)).
Finding 4, variable named mutex that is used to create the read lock for the thread (mutex = threading.RLock()).Finding 5, method named acquire(), it takes an optional wait flag, which can be used to avoid blocking if the lock is held by someone else.
Finding 6, variable named running that is used to count the number of running threads.
Finding 7, each time when TestThread() is running, console will print out a thread ID and the expected running time. Then the method named sema.acquire() will check the thread number whether is over 3 or not, if no, mutex will create a read lock for the waiting thread, then adding 1 to the variable named running.
Finding 8, when one of three thread has been running completely, mutex will release the read lock of that thread and update the value of variable named running by subtracting 1, then print out that task had been done. Afterwards, one of waiting thread will be locked. This processes are running in loop until 10 threads have run completely.
沒有留言:
發佈留言