ユーザ用ツール

サイト用ツール


サイドバー



最近の更新



Tag Cloud

タグ数量
9
10
1
3
1
2
17
7
1
1
4
13
4
1
2
314
1
9
2
7
21
5
1
31
3
3
1
6
1
1
46
1
3
3
1
1
1
1
1
1
33
46
7
9
10
8
10
3
21
2
9
2
2
6
9
1
1
6
12
4
3
3
2
1
8
2
4
1
6
30
2
12
5
3
1
1
2
3
2
1
3
4
3
3
4
2
2
1
1
2
1
2
1
2
1
27
2
1
3
2
2
1
1
2
3
17
5
9
1
1
2
17
2
6
1
2
12
1
3
1
1
4
11
1
6
4
2
7
1
3
3
13
1
4
1
1
10
3
1
17
3
1
5
1
2
1
1
2
9
2
2
3
2
1
3
1
3
1
2
2
2
1
2
6
1
4
3
5
1
3
1
3
3
2
1
1
30
1
3
3
1
1
1
5
5
1
36
2
4
2
1
2
2
3
1
1
1
4
1
2
1
3
1
1
1
2
5
2
5
2
1
1
1
5
3
2
4
6
1
2
2
27
1
1
3
4
1
1
2
1
1
2
1
1
1
1
2
1
1
1
1
1
20
7
1
6
1
1
3
1
2
2
1
2
1
1
1
1
1
1
2
1
1
2
1
1
1
1
1
1
1
5
2
1
1
2
2
2
1
1
2
1
1
12
1
1
1
1
1
1
1
1
1
1
1
1
1
2
1
1
1
1
2
15_python:04_parallel

04 Python 並列処理

parallel.py

import time
from concurrent.futures import ThreadPoolExecutor
from logging import StreamHandler, Formatter, INFO, getLogger

def init_logger():
    handler = StreamHandler()
    handler.setLevel(INFO)
    handler.setFormatter(Formatter("[%(asctime)s] [%(threadName)s] %(message)s"))
    logger = getLogger()
    logger.addHandler(handler)
    logger.setLevel(INFO)
    
def task(v):
    getLogger().info("%s start", v)
    time.sleep(1.0)
    getLogger().info("%s end", v)
    
def main():
    init_logger()
    getLogger().info("main start")
    with ThreadPoolExecutor(max_workers=2, thread_name_prefix="thread") as executor:
        for i in range(5):
            executor.submit(task, i)
        getLogger().info("submit end")
    getLogger().info("main end")


if __name__ == "__main__":
    main()

実行結果

# python3.6 parallel.py
[2019-08-09 11:23:41,298] [MainThread] main start
[2019-08-09 11:23:41,300] [thread_0] 0 start
[2019-08-09 11:23:41,301] [thread_1] 1 start
[2019-08-09 11:23:41,301] [MainThread] submit end
[2019-08-09 11:23:42,302] [thread_0] 0 end
[2019-08-09 11:23:42,302] [thread_0] 2 start
[2019-08-09 11:23:42,302] [thread_1] 1 end
[2019-08-09 11:23:42,302] [thread_1] 3 start
[2019-08-09 11:23:43,303] [thread_0] 2 end
[2019-08-09 11:23:43,304] [thread_0] 4 start
[2019-08-09 11:23:43,304] [thread_1] 3 end
[2019-08-09 11:23:44,305] [thread_0] 4 end
[2019-08-09 11:23:44,305] [MainThread] main end
15_python/04_parallel.txt · 最終更新: 2019/08/09 11:27 by matsui

Yesterday:1556 Today:1564 Total:28723