Найти - Пользователи
Полная версия: Как работают Pipes?
Начало » Python для новичков » Как работают Pipes?
1
ivanzzzz
В модуле 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__'
то все хорошо. Как это работает?
py.user.next
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]$
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB