Skip to content
Damjan Georgievski edited this page Oct 28, 2018 · 2 revisions

Python-овиот стандарден threading.Thread креира класични системски нишки (thread) од оперативниот систем. Linux и Windows користат 2MB и 1MB адресен простор за секоја нишка, соодветно. Иако тие 1-2MB не се алоцирана меморија, сепак го ограничуваат бројот на нишки по процес. Да видиме на колку:

# Threading scalability example
import os
from time import sleep
from threading import Thread

# Before 
print open("/proc/%d/status" % os.getpid()).read()

l = []

# try to start 1000 - will fail sooner
for i in xrange(0, 1000): 
   try:
       t = Thread(target=sleep, args=(30,))
       t.start()
       l.append(t)
   except:
       print "%i threads created." % len(l)
       break


print open("/proc/%d/status" % os.getpid()).read()

# Wait for all the threads to finish
for t in l:
   t.join()

# End
print open("/proc/%d/status" % os.getpid()).read()

(кај мене на 32bit-на дистрибуција со 2GB рам - 237 нишки)

Сега истиот пример со gevent/greenlet кои имплементираат не-системски нишки, уште наречени и корутини или lightweight процеси/таскови. Стоилјади не се проблем, за милион веќе е потребен повеќе RAM:

import os, time
from gevent import Greenlet, sleep

print open("/proc/%d/status" % os.getpid()).read()

l = []
t1 = time.time()
for i in xrange(0, 100000):  # also try a milion :)
   t = Greenlet(sleep, 30)
   t.start()
   l.append(t)

t2 = time.time()
print "%i coroutines created in %d seconds." % (len(l), t2-t1)

print open("/proc/%d/status" % os.getpid()).read()

for t in l:
   t.join()

# End
print open("/proc/%d/status" % os.getpid()).read()