Title: Update multiprocessing example
Type: Stage: resolved
Components: Documentation Versions: Python 3.8
Status: closed Resolution:
Dependencies: Superseder:
Assigned To: davin Nosy List: Windson Yang, davin, docs@python, pitrou, zach.ware
Priority: normal Keywords:

Created on 2018-07-05 08:45 by Windson Yang, last changed 2018-07-08 04:15 by Windson Yang. This issue is now closed.

Messages (5)
msg321088 - (view) Author: Windson Yang (Windson Yang) * Date: 2018-07-05 08:45
The docs at give an example:

from multiprocessing import Process, Lock

def f(l, i):
        print('hello world', i)

if __name__ == '__main__':
    lock = Lock()

    for num in range(10):
        Process(target=f, args=(lock, num)).start()

and point out "For instance one can use a lock to ensure that only one process prints to standard output at a time...". I'm not sure this is a good enough example for the reader. The reader can't tell the difference between the function with l.acquire() or not, The output just shows in the terminal at the same time. So I think a better idea just add time.sleep(0.1) before print('hello world', i) like this:

        # do something here
        # time.sleep(0.1)
        print('hello world', i)

I can provide a pr if you guys like this idea.
msg321210 - (view) Author: Antoine Pitrou (pitrou) * (Python committer) Date: 2018-07-07 08:34
The example feels a bit artificial indeed, but I don't think adding a sleep() call would make it realistic.  Why would you protect sleep() with a lock?
msg321219 - (view) Author: Windson Yang (Windson Yang) * Date: 2018-07-07 15:43
Hello, @Antoine Pitrou. Maybe there is another way to let the reader know "only one process prints to standard output at a time" instead of sleep() function?
msg321220 - (view) Author: Antoine Pitrou (pitrou) * (Python committer) Date: 2018-07-07 15:47
To be frank, I don't think that matters much.  The user should understand what a lock is already, if they want to make use of multiprocessing fruitfully.  The example showcases how to create a lock and how to pass it to child processes (by giving it as a function parameter).  Printing to standard output is not the important thing here.

However if you want to improve this example, you could replace the acquire/release pair with a "with" statement.
msg321255 - (view) Author: Windson Yang (Windson Yang) * Date: 2018-07-08 04:14
Thank you, I think to use acquire() and release() may be better than with statement in this example. I will close this issue.
Date User Action Args
2018-07-08 04:15:01Windson Yangsetstatus: open -> closed
stage: resolved
2018-07-08 04:14:52Windson Yangsetmessages: + msg321255
2018-07-07 15:47:44pitrousetmessages: + msg321220
2018-07-07 15:43:37Windson Yangsetmessages: + msg321219
2018-07-07 08:34:50pitrousetnosy: + pitrou
messages: + msg321210
2018-07-06 02:30:50Windson Yangsetnosy: + zach.ware
2018-07-05 23:12:37rhettingersetassignee: docs@python -> davin

nosy: + davin
2018-07-05 08:45:49Windson Yangcreate