コスギデンサン >> 情報系メモ >> Python

Python - スレッド - スレッド間で変数グローバルを共有 2017/5
Version 3.6.1 on CentOS7

import logging
import traceback
import subprocess
import threading
import time

logging.basicConfig(level=logging.DEBUG, format='(%(threadName)s) %(message)s')

global_flag = False

def print_ps():
    i = 0
    while True:
        try:
            cmd = ['echo', 'i=' + str(i)]

            #buf = subprocess.check_call(cmd)
            buf = subprocess.check_output(cmd)
            print(buf)

        except:
            logging.debug(traceback.format_exc())

        if global_flag:
            break

        time.sleep(1)
        i = i + 1
    # End of for

#
# main
#
logging.debug("Start");

thread = threading.Thread(target=print_ps)
thread.start()

time.sleep(10)
global_flag = True

# スレッド終了待ち
thread.join()

logging.debug("End");
実行結果
(MainThread) Start
(Thread-1) b'i=0\n'
(Thread-1) b'i=1\n'
(Thread-1) b'i=2\n'
(Thread-1) b'i=3\n'
(Thread-1) b'i=4\n'
(Thread-1) b'i=5\n'
(Thread-1) b'i=6\n'
(Thread-1) b'i=7\n'
(Thread-1) b'i=8\n'
(Thread-1) b'i=9\n'
(Thread-1) b'i=10\n'
(MainThread) End