Issue 34051: Update multiprocessing example (original) (raw)

Created on 2018-07-05 08:45 by Windson Yang, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (5)
msg321088 - (view) Author: Windson Yang (Windson Yang) * Date: 2018-07-05 08:45
The docs at https://docs.python.org/3.8/library/multiprocessing.html#synchronization-between-processes give an example: from multiprocessing import Process, Lock def f(l, i): l.acquire() try: print('hello world', i) finally: l.release() 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: l.acquire() try: # 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.
History
Date User Action Args
2022-04-11 14:59:02 admin set github: 78232
2018-07-08 04:15:01 Windson Yang set status: open -> closedstage: resolved
2018-07-08 04:14:52 Windson Yang set messages: +
2018-07-07 15:47:44 pitrou set messages: +
2018-07-07 15:43:37 Windson Yang set messages: +
2018-07-07 08:34:50 pitrou set nosy: + pitroumessages: +
2018-07-06 02:30:50 Windson Yang set nosy: + zach.ware
2018-07-05 23:12:37 rhettinger set assignee: docs@python -> davinnosy: + davin
2018-07-05 08:45:49 Windson Yang create