30.11.2014 Views

A4 portrait - PET: Python Entre Todos - Python Argentina

A4 portrait - PET: Python Entre Todos - Python Argentina

A4 portrait - PET: Python Entre Todos - Python Argentina

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Context managers 12<br />

print "Starting to work"<br />

time.sleep(2)<br />

print "Finished working"<br />

def main():<br />

print "Starting the main program"<br />

thread = processing.Process(target=trabajador)<br />

print "Launching thread"<br />

thread.start()<br />

print "Thread has been launched"<br />

# isAlive() is False when the thread ends.<br />

while thread.isAlive():<br />

# Here you would have the code to make the app<br />

# look "alive", a progress bar, or maybe just<br />

# keep on working as usual.<br />

print "The thread is still running"<br />

# Wait a little bit, or until the thread ends,<br />

# whatever's shorter.<br />

thread.join(.3)<br />

print "Program ended"<br />

# Important: the modules should not execute code<br />

# when they are imported<br />

if __name__ == '__main__':<br />

main()<br />

Yes, the only change is import multiprocessing instead of import threading and<br />

Process instead of Thread. Now the worker function runs in a separate <strong>Python</strong><br />

interpreter. Since they are separate processes, this will use as many cores as<br />

processes you have, so it may be much faster on a modern computer.<br />

I mentioned deadlocks earlier. You may believe that with a little care, if you place<br />

locks around variables you can avoid them. Well, no. Let’s see two functions f1 and<br />

f2 which use two variables x and y protected by locks lockx and locky.<br />

# -*- coding: utf-8 -*-<br />

import threading<br />

import time<br />

x = 4<br />

y = 6<br />

lock_x = threading.Lock()<br />

lock_y = threading.Lock()<br />

def f1():<br />

lock_x.acquire()<br />

time.sleep(2)<br />

lock_y.acquire()<br />

time.sleep(2)<br />

lock_x.release()<br />

lock_y.release()<br />

def f2():<br />

lock_y.acquire()<br />

time.sleep(2)<br />

lock_x.acquire()<br />

time.sleep(2)<br />

lock_y.release()<br />

lock_x.release()<br />

def main():<br />

<strong>PET</strong>: English Translation (Issue 1, August 2010) — http://revista.python.org.ar

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!