thread example question

Rodrick Brown rodrick.brown at gmail.com
Wed Jan 18 00:22:20 EST 2012


Can any idea help me figure out why the following output is sequential? I'm
running this example on a 4 core system.
I would expect the output to look random.

import _thread as thread
import time

class thread_counter(object):
    def __init__(self, thr_cnt, sleep_int):
        self.thr_cnt = thr_cnt
        self.sleep_int = sleep_int

def counter(myId, count):
    for i in range(count):
        time.sleep(1)
        print('[{}] => {}'.format(myId, i))

def main():
    for i in range(5):
        thread.start_new_thread(counter, (i, 5))
        time.sleep(6)
        print('Main thread exiting..')

if __name__ == '__main__':
    main()


[0] => 0
[0] => 1
[0] => 2
[0] => 3
[0] => 4
Main thread exiting..
[1] => 0
[1] => 1
[1] => 2
[1] => 3
[1] => 4
Main thread exiting..
[2] => 0
[2] => 1
[2] => 2
[2] => 3
[2] => 4
Main thread exiting..
[3] => 0
[3] => 1
[3] => 2
[3] => 3
[3] => 4
Main thread exiting..
[4] => 0
[4] => 1
[4] => 2
[4] => 3
[4] => 4
Main thread exiting..
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120118/6892e7cb/attachment.html>


More information about the Python-list mailing list