Уведомления

Группа в Telegram: @pythonsu

#1 Ноя. 25, 2016 11:14:06

ivanzzzz
Зарегистрирован: 2016-08-23
Сообщения: 30
Репутация: +  0  -
Профиль   Отправить e-mail  

Как работают Pipes?

В модуле multiprocessing, Pipes может работать только с 2 потоками?

попробовал так:

 from multiprocessing import Process, Pipe
def f(conn):
    conn.send([42, None, 'hello'])
    conn.close()
def p(parent_conn):
    print parent_conn.recv()
    
if __name__ == '__main__':
    parent_conn, child_conn = Pipe()
    p = Process(target=f, args=(child_conn,))
    p.start()
    p.join()
    p1 = Process(target=p, args=(parent_conn,))
    p1.start()
    
    #print parent_conn.recv()   # prints "[42, None, 'hello']"
    p1.join()

и кучу ошибок словил. но если
 print parent_conn.recv()
в
 if __name__ == '__main__'
то все хорошо. Как это работает?

Отредактировано ivanzzzz (Ноя. 25, 2016 11:14:27)

Офлайн

#2 Ноя. 26, 2016 00:44:12

py.user.next
От:
Зарегистрирован: 2010-04-29
Сообщения: 9993
Репутация: +  857  -
Профиль   Отправить e-mail  

Как работают Pipes?

ivanzzzz
В модуле multiprocessing, Pipes может работать только с 2 потоками?
Да, он может только с двумя потоками работать, потому что они захватывают ресурсы и не отпускают.
python.org. Pipes
Note that data in a pipe may become corrupted if two processes (or threads) try to read from or write to the same end of the pipe at the same time. Of course there is no risk of corruption from processes using different ends of the pipe at the same time.

 #!/usr/bin/env python3
 
from multiprocessing import Process, Pipe
import time
 
def sender(conn):
    conn.send([42, None, 'hello'])
    conn.close()
    print('sender:', "I've ended")
 
def printer(conn):
    for i in conn.recv():
        print(i)
        time.sleep(2)
    print('printer:', "I've ended")
 
if __name__ == '__main__':
    inend, outend = Pipe()
    th_sender = Process(target=sender, args=(inend,))
    th_printer = Process(target=printer, args=(outend,))
    th_sender.start()
    th_printer.start()
    th_printer.join()
    th_sender.join()
    time.sleep(2)
    print('main:', "I've ended")

Вывод
[guest@localhost py]$ ./t.py 
sender: I've ended
42
None
hello
printer: I've ended
main: I've ended
[guest@localhost py]$



Отредактировано py.user.next (Ноя. 26, 2016 14:49:03)

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version