コード例 #1
0
def print_chopsticks_used():
    mutex_chopsticks_used.wait()
    print("[", end="")
    for i in range(N_PHILOSOPHERS):
        print(print_chopstick(chopsticks_used[i]), end="")
        print(",", end="")

    print("]")
    mutex_chopsticks_used.signal()


def philosopher(i):
    while True:
        print("%i is thinking..." % i)
        # time.sleep(i + 1)
        print("%i is done thinking and ready to eat" % i)
        print_chopsticks_used()
        get_chopsticks(i)
        print("%i is starting to eat" % i)
        print_chopsticks_used()
        # time.sleep(i + 1)
        print("%i is done eating" % i)
        put_chopsticks(i)
        print_chopsticks_used()


watcher()

[Thread(philosopher, i) for i in range(N_PHILOSOPHERS)]
コード例 #2
0
# rendezvous

# desired: (a1 and b1) < (a2 and b2)

from sync import Thread, Semaphore, watcher

sem1 = Semaphore(0)
sem2 = Semaphore(0)


def child1():
    print("a1")
    sem1.signal()
    sem2.wait()
    print("a2")


def child2():
    print("b1")
    sem2.signal()
    sem1.wait()
    print("b2")


watcher()

threada = Thread(child1)
threadb = Thread(child2)
コード例 #3
0
from sync import Thread, Semaphore, watcher

mutex = Semaphore(1)
count = 0


def child1():
    global count
    mutex.wait()
    print("a1")
    count += 1
    mutex.signal()


def child2():
    global count
    mutex.wait()
    print("b1")
    count += 1
    mutex.signal()


watcher()

threada = Thread(child1)
threadb = Thread(child2)

threada.join()
threadb.join()
print(count)