Python - multithreading / multiprocessing, very strange problem.

Posted by orokusaki on Stack Overflow See other posts from Stack Overflow or by orokusaki
Published on 2010-04-14T21:12:59Z Indexed on 2010/04/14 21:13 UTC
Read the original article Hit count: 639

import uuid
import time
import multiprocessing


def sleep_then_write(content):
    time.sleep(5)
    print(content)

if __name__ == '__main__':
    for i in range(15):
        p = multiprocessing.Process(target=sleep_then_write,
                                    args=('Hello World',))
        p.start()

print('Ah, what a hard day of threading...')

This script output the following:

Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
AAh, what a hard day of threading..
h, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Ah, what a hard day of threading...
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

Firstly, why the heck did it print the bottom statement sixteen times (one for each process) instead of just the one time?

Second, notice the AAh, and h, about half way down; that was the real output. This makes me wary of using threads ever, now.

(Windows XP, Python 2.6.4, Core 2 Duo)

© Stack Overflow or respective owner

Related posts about multithreading

Related posts about multiprocessing