Welcome, guest | Sign In | My Account | Store | Cart

This recipe demonstrates a multithreaded application. The code is short but should be an easy example of HOW-TO.

Python, 37 lines
 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
from math import e, pi
from os.path import basename
from sys import argv
from threading import currentThread, Thread
from time import ctime, sleep

NAP_TIME = 1
BUSY_TIME = 40000

def main():
    try:
        if len(argv) != 3:
            raise Exception
        engine(int(argv[1]), int(argv[2]))
    except:
        print basename(argv[0]), '<threads> <seconds>'

def engine(threads, seconds):
        print 'Suite starting at', ctime()
        for thread in range(threads):
            temp = Thread(target = threadWork)
            temp.setDaemon(True)
            temp.start()
        sleep(seconds)

def threadWork():
    while True:
        try:
            for i in range(BUSY_TIME):
                y = pi ** e
            sleep(NAP_TIME)
            print currentThread().getName(), 'just woke up.'
        except:
            pass

if __name__ == '__main__':
    main()

One of the main reasons that this code is being presented here is this -- how do you prevent crashing threads from printing errors? The platform in this case is Windows.

1 comment

Stephen Chappell (author) 18 years, 2 months ago  # | flag

Threads. In the example, all threads that are created are Daemon threads. When the main thread finishes sleeping, errors are sometimes (but not always) printed to the screen. What can be done to prevent this? The program should just close without errors being printed. The solution should be simple and allow the use of the Daemon threads if possible.