Skip to content

Instantly share code, notes, and snippets.

@silviot silviot/gist:2761278

Created May 21, 2012
Embed
What would you like to do?
"""
I have a challenge for you:
- Print "Hello World" using any language.
- Each character must be printed from its own, unique thread
That's it. Obviously, as there's no guarantee that the threads will operate in the order you start them, you have to make your program thread safe to ensure the output is printed in the right order.
And, because this is code golf, the shortest program wins.
Source: http://codegolf.stackexchange.com/questions/5871/helolw-rdlo-a-threading-challenge
"""
# Ok. First we patch Threading.start to point out that the only
# python answer so far is utterly wrong
import threading
import random, time
original_run = threading.Thread.run
def myRun(self):
tosleep = random.randint(0,200)/1000.0
time.sleep(tosleep)
original_run(self)
threading.Thread.run = myRun
# And now the utterly wrong code:
import sys,threading as t
for x in "Hello World":t.Thread(None,sys.stdout.write,x,x).start()
# On my machine produced:
dle loHoWrl
llHroW leod
lllW eordHo
# etc etc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.