Проблема с Python потоками и семафорами - PullRequest
0 голосов
/ 27 марта 2020

У меня есть четыре процесса (function0, function1, function2 и function3), и я хочу напечатать сообщение «hello world world from python» 1000 раз. Моя проблема в том, что программа печатает только «Привет, мир из мира» и застревает там.

Ниже мой код:

import threading

sem0= threading.Semaphore(1)
sem1 = threading.Semaphore(0)
sem2 = threading.Semaphore(0)
sem3 = threading.Semaphore(0)

def function0():
    for i in range(0, 1000):
        sem0.acquire()
        print("hello", end=" ")
        sem1.release()
        sem1.release()

def function1():
    for i in range(0, 2000):
        sem1.acquire()
        print("world", end=" ")
        if i % 2 != 0:
            sem2.release()

def function2():
    for i in range(0, 2000):
        sem2.acquire()
        print("from", end=" ")
        if i % 2 != 0:
            sem3.release()

def function3():
    for i in range(0, 1000):
        sem3.acquire()
        print("python\n")
        sem0.release()

thread0 = threading.Thread(target=function0)
thread1 = threading.Thread(target=function1)
thread2 = threading.Thread(target=function2)
thread3 = threading.Thread(target=function3)

threads = []

threads.append(thread0)
threads.append(thread1)
threads.append(thread2)
threads.append(thread3)

for t in threads:
    t.start()

здесь вывод

1 Ответ

0 голосов
/ 27 марта 2020

Когда я запускаю его, я не получаю вывод. В любом случае:

Вы застряли, потому что пытаетесь сделать слишком много семафоров на семафор. Если семафор инициализирован со значением 1, вы можете сделать только один acquire; второй будет блокироваться до тех пор, пока на нем не будет выполнено release.

Следующий код, например, делает то, что вы ожидаете (я изменил его для печати только 10 раз и удалил лишнюю новую строку из print заявление):

import threading

sem0 = threading.Semaphore(1)
sem1 = threading.Semaphore(0)
sem2 = threading.Semaphore(0)
sem3 = threading.Semaphore(0)

def function0():
    for _ in range(10):
        sem0.acquire()
        print("hello", end=" ")
        sem1.release()

def function1():
    for _ in range(10):
        sem1.acquire()
        print("world", end=" ")
        sem2.release()
        sem2.release()

def function2():
    for _ in range(10):
        sem2.acquire()
        print("from", end=" ")
        sem2.acquire()
        print("from", end=" ")
        sem3.release()

def function3():
    for _ in range(10):
        sem3.acquire()
        print("python")
        sem0.release()

thread0 = threading.Thread(target=function0)
thread1 = threading.Thread(target=function1)
thread2 = threading.Thread(target=function2)
thread3 = threading.Thread(target=function3)

threads = []

threads.append(thread0)
threads.append(thread1)
threads.append(thread2)
threads.append(thread3)

for t in threads:
    t.start()

Отпечатки:

hello world from from python
hello world from from python
hello world from from python
hello world from from python
hello world from from python
hello world from from python
hello world from from python
hello world from from python
hello world from from python
hello world from from python

Python Демо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...