thread example question

2012-01-17 Thread Rodrick Brown
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..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: thread example question

2012-01-17 Thread Mark Hammond

On 18/01/2012 4:22 PM, Rodrick Brown wrote:

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))


I think you meant for the following 2 lines to be outside the loop (ie, 
to be dedented one level).  Once you do that the output is as *I* expect :)


Mark


 time.sleep(6)
 print('Main thread exiting..')

if __name__ == '__main__':
 main()



--
http://mail.python.org/mailman/listinfo/python-list