-
Notifications
You must be signed in to change notification settings - Fork 0
/
threads2.py
88 lines (63 loc) · 2.16 KB
/
threads2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#/bin/python
# Program for messing w/ threads and options
import threading
import Queue
import time
import logging
from optparse import OptionParser
continue_threads = True
class WorkerThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def finish(self):
self.cont = False
def run(self):
print "In WorkerThread"
while continue_threads == True:
counter = self.queue.get()
# thread Logic goes here
print "Ordered to sleep for %d seconds!"%counter
time.sleep(counter)
print "Finished sleeping for %d seconds"%counter
self.queue.task_done()
def main():
# Setup the command line arguments.
optp = OptionParser()
# Output verbosity options
optp.add_option('-q', '--quiet', help='set logging to ERROR',
action='store_const', dest='loglevel',
const=logging.ERROR, default=logging.INFO)
optp.add_option('-d', '--debug', help='set logging to DEBUG',
action='store_const', dest='loglevel',
const=logging.DEBUG, default=logging.INFO)
optp.add_option('-v', '--verbose', help='set logging to COMM',
action='store_const', dest='loglevel',
const=5, default=logging.INFO)
# Option for number of threads
optp.add_option("-t", "--threads", dest="threads",
help="The number of threads to spawn")
opts, args = optp.parse_args()
if opts.threads is None:
opts.threads = raw_input("How threads do you want to spawn: ")
# Setup logging.
logging.basicConfig(level=opts.loglevel,
format='%(levelname)-8s %(message)s')
# Main Event Loop:
try:
queue = Queue.Queue()
for i in range(int(opts.threads)):
print "Creating WorkerThread : %d"%i
worker = WorkerThread(queue)
worker.setDaemon(True)
worker.start()
print "WorkerThread %d Created!"%i
for j in range(int(opts.threads)):
queue.put(j)
queue.join()
except (KeyboardInterrupt, EOFError) as e:
continue_threads = False
exit(0)
print "All tasks complete!"
if __name__ == '__main__':
main()