Last active
September 5, 2020 00:13
-
-
Save myaosato/6c807944574cd51cb88d1b78cb551fc8 to your computer and use it in GitHub Desktop.
Pythonプロセス並列化お試し
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 1秒後, 2秒後 3秒後に印字されるものと, | |
| # 2秒後, 3秒後 に印字される | |
| import time | |
| import sys | |
| from multiprocessing import Process, Value, set_start_method | |
| set_start_method('fork') | |
| def f(xs, flg): | |
| cnt = 0 | |
| for x in xs: | |
| time.sleep(x) | |
| if (flg.value == 1): | |
| return | |
| print(cnt, ': ', time.time()) | |
| if (cnt == 2): | |
| flg.value = 1 | |
| cnt += 1 | |
| return | |
| def main(): | |
| flg = Value('B', 0, lock = False) | |
| for xs in [[1, 1, 1], [2, 1, 1]]: | |
| p = Process(target=f, args=(xs, flg)) | |
| p.start() | |
| if __name__ == '__main__': | |
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 1秒後, 1+3秒後 に印字されるものと, 2秒後と2+4秒後に印字される | |
| import time | |
| import sys | |
| from multiprocessing import Process, set_start_method | |
| set_start_method('fork') | |
| def f(xs): | |
| for x in xs: | |
| time.sleep(x) | |
| print(x, ': ', time.time()) | |
| sys.exit() | |
| def main(): | |
| for xs in [[1, 3], [2, 4]]: | |
| p = Process(target=f, args=(xs,)) | |
| p.start() | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment