Thursday, March 4, 2010

March Madness Challenge - MMC04

Working with the python documentation some kind of sucks. Maybe its me.... Putting code into blogger is still a problem, will see what I can do about that.

Threading is todays topic. A user specified number of threads are going to sleep for random 1 to 5 seconds and then try to access a shared counter. Whatever number of threads you set as argument, the counter should have the some value. I'm still a little bit confused about when to use "import" or "from x import y".



1 #! /usr/bin python
2
3 import random
4 import thread
5 import time
6
7 counter = 0
8
9 def threadFunc(threadID, lock):
10 print 'Thread %d START' % threadID
11 sleep = random.randint(1,5)
12 print 'Thread %d will sleep for %d seconds' % (threadID,sleep)
13 time.sleep(sleep)
14 lock.acquire()
15 try:
16 global counter
17 counter += 1
18 finally:
19 lock.release()
20 print 'Thread %d END' % threadID
21
22 def runThreads(threadCount):
23 cntLock = thread.allocate_lock()
24
25 for i in range(int(threadCount)):
26 t = Thread(target=threadFunc, args=(i,cntLock))
27 t.start()
28
29 if __name__ == '__main__':
30 print '***** MMC04 *****'
31
32 from threading import Thread
33
34 from optparse import OptionParser
35 parser = OptionParser()
36 parser.add_option("-t", "--threads", dest="threadCount", default='1',
37 help='number of threads')
38 (options, args) = parser.parse_args()
39
40 runThreads(options.threadCount)
41
42 time.sleep(6)
43 print 'Counter = %d' % counter
44

No comments:

Post a Comment