Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Python Threads (You're excited already,)

Name: Anonymous 2012-02-16 0:52


####################################################
# uses simple shared global data (not mutexes) to
# know when threads are done in parent/main thread;
####################################################

import thread
stdoutmutex = thread.allocate_lock( )
exitmutexes = [0] * 10

def counter(myId, count):
    for i in range(count):
        stdoutmutex.acquire( )
        print '[%s] => %s' % (myId, i)
        stdoutmutex.release( )
    exitmutexes[myId] = 1  # signal main thread

for i in range(10):
    thread.start_new(counter, (i, 100))

while 0 in exitmutexes: pass
print 'Main thread exiting.'




[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => 0
[7] => 0
[8] => 0
[9] => 0
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 1
[6] => 1
[7] => 1
[8] => 1
[9] => 1
[0] => 2
[1] => 2
[2] => 2
[3] => 2
[4] => 2
[5] => 2
[6] => 2
[7] => 2
[8] => 2
[9] => 2
[0] => 3
~~~ ... BunchAShitYouCareEvenLessAbout ... ~~~
[6] => 98
[7] => 98
[8] => 98
[9] => 98
[0] => 99
[1] => 99
[2] => 99
[3] => 99
[4] => 99
[5] => 99
[6] => 99
[7] => 99
[8] => 99
[9] => 99
Main thread exiting.


So I don't get this. Why does it count the numbers in order? Wouldn't a counter thread acquire itself as soon as it released itself? I don't understand why any of this is in order. I get why the processes can be out of order, but not why it counts in order.

Name: Anonymous 2012-02-19 21:21

>>2 & >>15 here.

>>19

That will happen.

>>17

DING DING DING.

Okay, since is the third time I'll break down and post some code.

#!/usr/bin/env python

from threading import Thread
exitmutexes = [0] * 10

def counter(myId, count):
    for i in range(count):
        print '[%s] => %s' % (myId, i)
    exitmutexes[myId] = 1  # signal main thread

for i in range(10):
    t = Thread(target=counter, args=(i,100,))
    t.start()

while 0 in exitmutexes: pass
print 'Main thread exiting.'


Run it a couple of times to check the output. It prints all types of out of order because it processes whatever it wants whenever it gets it's hands on it.

inb4 didn't color code, not pythonic, or other such neckbeard shitstorm

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List