python-다선정 소연련

11726 단어

제목: 다중 스레드의threading 모듈 연습

# encoding=utf-8


#  
#   3  
# def coding():
#     for x in range(3):
#         print(' %s' %x)
#         time.sleep(1)
#
# def drawing():
#     for x in range(3):
#         print(' %s' %x)
#         time.sleep(1)
#
# def main():
#     coding()
#     drawing()
#
# if __name__ == '__main__':
#     main()

import time
import threading
#  :
#   3  
def coding():
    for x in range(3):
        print(' %s' %threading.current_thread())
        time.sleep(1)

def drawing():
    for x in range(3):
        print(' %s' %threading.current_thread())
        time.sleep(1)

def main():
    # threading.Thread  
    # target  
    #  : , 
    #   coding():  
    t1 = threading.Thread(target=coding)
    t2 = threading.Thread(target=drawing)
    t1.start()
    t2.start()
    print(threading.enumerate())

if __name__ == '__main__':
    main()



2. Thread 클래스:
# encoding=utf-8

import threading
import time
class CodingThread(threading.Thread):
    def run(self):
        for x in range(3):
            print(' %s' %threading.current_thread())
            time.sleep(1)
class DrawingThread(threading.Thread):
    def run(self):
        for x in range(3):
            print(' %s' %threading.current_thread())
            time.sleep(1)

def main():
    t1 = CodingThread()
    t2= DrawingThread()
    t1.start()
    t2.start()
if __name__ == '__main__':
    main()



3. 글로벌 변수 공유 문제
# encoding=utf-8
import threading

VALUE = 0
#  
gLock = threading.Lock()
def add_value():
    #   global  
    global VALUE
    #  
    gLock.acquire()
    #  
    for x in range(10000000):
        VALUE +=1
    #  
    gLock.release()
    print('value, %d' %VALUE)
def main():
    for x in range(2):
        t =threading.Thread(target=add_value())
        t.start()

if __name__ == '__main__':
    main()



좋은 웹페이지 즐겨찾기