0

I am new to python multithreading and confusing with the code beblow:

#!/usr/bin/env python

import thread
from time import sleep, ctime

loops = [4, 2]

def loop(nloop, nsec, lock):
    print 'start loop', nloop, 'at:', ctime()
    sleep(nsec)
    print 'loop', nloop, 'done at:', ctime()
    lock.release()

def main():
    print 'starting at:', ctime()
    locks = []
    nloops = range(len(loops))

    for i in nloops:
        lock = thread.allocate_lock()
        lock.acquire()
        locks.append(lock)

    for i in nloops:
        thread.start_new_thread(loop,
                    (i, loops[i], locks[i]))

    for i in nloops:
        while locks[i].locked():
            pass

    print 'all done at:', ctime()

if __name__ == '__main__':
    main()

When I tried to run I got the result below

starting at: Fri Aug 03 17:07:20 2012
start loopstart loop  01  at:at:  Fri Aug 03 17:07:20 2012Fri Aug 03 17:07:20 20
12

loop 1 done at: Fri Aug 03 17:07:22 2012
loop 0 done at: Fri Aug 03 17:07:24 2012
all done at: Fri Aug 03 17:07:24 2012

as you see, the "start" outputs of these two thread were mixed up and I guess there are something conflict, but I don't understand the details and how to fix it, can anyone help me? thanks.

ZRJ
  • 181
  • 1
  • 7

1 Answers1

0

This is pretty usual situation when you work with threads and I/O - threads are writing to stdout simultaneously and their messages become mixed.

There should be nothing wrong with your multithreading implementation.

Roman Bodnarchuk
  • 29,461
  • 12
  • 59
  • 75