===== Concorrenza e Threading =====
In questa lezione abbiamo visto i principi fondamentali della [[wp>Concurrency_(computer_science)|concorrenza]], e piu' i particolare il modello di programmazione a thread.
Dal punto di vista teorico, abbiamo introdotto i concetti di memoria condivisa e passaggio di messaggi, nonche' alcuni modelli di concorrenza ([[wp>Tuple_space|spazio di tuple]], [[wp>Actor_model|modello ad attori]], [[wp>Process_calculus|algebre dei processi]]).
In fondo alla pagina trovate gli esempi di codice visti a lezione.
==== Concurrency & Threading ====
In this lecture we have studied the fundamentals of [[wp>Concurrency_(computer_science)|concurrency]], and specifically the thread programming model.
On the theoretical side, we've introduced the concepts of shared memory and message passing, as well as some concurrency models ([[wp>Tuple_space|tuple space]], [[wp>Actor_model|actor model]], [[wp>Process_calculus|process calculus]]).
=== Esempi di programmazione con i Thread/Code samples for Threading ===
**Hello, World**
#!/usr/bin/python
from threading import Thread
from time import sleep
from random import randint
def hello():
sleep(randint(0,3))
print 'Hello'
def world():
sleep(randint(0,3))
print 'World'
Thread(target=hello).start()
Thread(target=world).start()
**A Producer/Consumer Example**
#!/usr/bin/python
from threading import Thread, Event
from random import randint
d=0
e=[Event(),Event()]
e[1].set()
def hello(e):
for i in range(5) :
e[1].wait()
global d
d=d+1
e[0].set()
e[1].clear()
def world(e):
for i in range(5) :
e[0].wait()
global d
print d*2
e[0].clear()
e[1].set()
Thread(target=hello, args=(e,)).start()
Thread(target=world, args=(e,)).start()