Python의 프로세스 스레드 협정에 관한threading 모듈 (2) Lock, RLock 대상 및Semaphore, BoundedSemaphore 대상

38470 단어 파이썬 개발

Python의 프로세스 스레드 협정에 관한threading 모듈 (2) Lock, RLock 대상 및Semaphore, BoundedSemaphore 대상


스레드 잠금: 스레드 사이는 무작위로 스케줄링되고 모든 스레드는 cpu에서 지정한 수량의 바이트 코드(100)만 실행하기 때문에 여러 스레드가 같은 데이터를 동시에 수정할 때 더러운 데이터가 발생할 수 있습니다. 이를 피하기 위해 스레드 잠금이 생겨나고 같은 시간에 한 스레드가 작업을 수행할 수 있습니다.

인스턴스 1:


자물쇠가 없는 경우 cpu 성능이 좋지 않을 때 더러운 데이터가 발생하기 쉽다
# _*_coding:utf-8_*_
import threading
from time import sleep, ctime


maxlink = 10
# A pool of thread maxlink
thread_pool = []
# A pool of thread that save instantiation threads    
count = 0
# A global var

def loop(index):
    """A function for sleep sometime s """
    print "start loop %s at: " % index, ctime()
    global count
    count += 1
    sleep(2)
    print "end loop %s at: " % index, ctime()

def Thread_Pool(*arg):
    """A function that create and save instantiation
     of threading to thread pool"""
    func, LN = arg
    for i in range(LN):
        t = threading.Thread(target=func, args=(i,))
        thread_pool.append(t)

def Thread_Start(arg):
    """A function that represents a thread of control."""
    for i in range(arg):
        thread_pool[i].start()
    for i in range(arg):
        thread_pool[i].join()

def main():
    """A function of main"""
    print "process start at: ".upper(), ctime()
    Thread_Pool(loop, maxlink)
    Thread_Start(maxlink)
    print "process end at: ".upper(), ctime(), "now count :", count


if __name__ == '__main__':
main()

실행 결과:
PROCESS START AT:  Fri Apr 28 16:49:28 2017
start loop 0 at:  Fri Apr 28 16:49:28 2017
start loop 1 at:  Fri Apr 28 16:49:28 2017
start loop 2 at:  Fri Apr 28 16:49:28 2017
start loop 3 at:  Fri Apr 28 16:49:28 2017
start loop 4 at:  Fri Apr 28 16:49:28 2017
start loop 5 at:  Fri Apr 28 16:49:28 2017
start loop 6 at:  Fri Apr 28 16:49:28 2017
start loop 7 at:  Fri Apr 28 16:49:28 2017
start loop 8 at:  Fri Apr 28 16:49:28 2017
start loop 9 at:  Fri Apr 28 16:49:28 2017
end loop 0 at: end loop 2 at: end loop 1 at:    Fri Apr 28 16:49:30 2017Fri Apr 28 16:49:30 2017Fri Apr 28 16:49:30 2017


end loop 6 at: end loop 3 at: end loop 7 at: end loop 5 at: end loop 4 at: end loop 8 at: end loop 9 at:       Fri Apr 28 16:49:30 2017Fri Apr 28 16:49:30 2017Fri Apr 28 16:49:30 2017Fri Apr 28 16:49:30 2017Fri Apr 28 16:49:30 2017Fri Apr 28 16:49:30 2017Fri Apr 28 16:49:30 2017






PROCESS END AT:  Fri Apr 28 16:49:30 2017 now count : 7

인스턴스 2:


Lock 메서드 정보
#_*_coding:utf-8_*_
import threading
from time import sleep, ctime


_maxlink = 10
# A pool of thread max-link
thread_pool = []
# A list for saving instantiations of thread
lock_pool = []
# A list for saving instantiation of Lock
count = 0
# A global var


def loop(*args):
    """ A function for sleep sometime """
    _index,_lock = args
    print "start loop %s at: " % _index, ctime()
    _lock.acquire(2)
    # 
    global count
    count += 1
    _lock.release()
    # 
    sleep(2)
    print "end loop %s at: " % _index, ctime()


def Thread_Pool(*arg):
    """A function that create and save instantiation
     of threading to thread pool"""
    _func, _LN ,_Lock= arg
    for i in range(_LN):
        t = threading.Thread(target=_func, args=(i,_Lock[i]))
        thread_pool.append(t)

def Lock_Pool(arg):
    """A function that create max-link instantiations of Lock"""
    for i in range(arg):
        _L = threading.Lock()
        # 
        lock_pool.append(_L)
    return lock_pool

def Thread_Start(arg):
    """A function that represents a thread of control."""
    for i in range(arg):
        thread_pool[i].start()
    for i in range(arg):
        thread_pool[i].join()

def main():
    """ A function of main """
    print "process start at: ".upper(), ctime()
    Lock_Pool(_maxlink)
    Thread_Pool(loop, _maxlink,lock_pool)
    Thread_Start(_maxlink)
    print "process end at: ".upper(), ctime(),"now count :",count


if __name__ == '__main__':
main()

실행 결과:
PROCESS START AT:  Fri Apr 28 16:50:10 2017
start loop 0 at:  Fri Apr 28 16:50:10 2017
start loop 1 at:  Fri Apr 28 16:50:10 2017
start loop 2 at:  Fri Apr 28 16:50:10 2017
start loop 3 at:  Fri Apr 28 16:50:10 2017
start loop 4 at:  Fri Apr 28 16:50:10 2017
start loop 5 at:  Fri Apr 28 16:50:10 2017
start loop 6 at:  Fri Apr 28 16:50:10 2017
start loop 7 at:  Fri Apr 28 16:50:10 2017
start loop 8 at:  Fri Apr 28 16:50:10 2017
start loop 9 at:  Fri Apr 28 16:50:10 2017
end loop 0 at:  Fri Apr 28 16:50:12 2017
end loop 2 at: end loop 3 at:  end loop 5 at: end loop 4 at:  Fri Apr 28 16:50:12 2017end loop 1 at:   Fri Apr 28 16:50:12 2017
 Fri Apr 28 16:50:12 2017Fri Apr 28 16:50:12 2017
Fri Apr 28 16:50:12 2017


end loop 7 at: end loop 8 at: end loop 6 at:  end loop 9 at:   Fri Apr 28 16:50:12 2017 Fri Apr 28 16:50:12 2017Fri Apr 28 16:50:12 2017
Fri Apr 28 16:50:12 2017


PROCESS END AT:  Fri Apr 28 16:50:12 2017 now count : 10

인스턴스 3:


RLock 메서드
#_*_coding:utf-8_*_
import threading
from time import sleep, ctime


_max_link = 10
# A pool of thread max-link
thread_pool = []
# A pool of thread that save instantiation threads    
count = 0
# A global var


def loop(*args):
    '''A function for sleep sometime s ,and make global count ++'''
    _index,_lock = args
    print "start loop %s at: " % _index, ctime()
    _lock.acquire()
    # 
    global count
    count += 1
    _lock.release()
    # 
    sleep(2)
    print "end loop %s at: " % _index, ctime()


def Thread_Pool(*arg):
    """A function that create instantiations of threading"""
    _func, _LN ,_Lock= arg
    for i in range(_LN):
        t = threading.Thread(target=_func, args=(i,_Lock))# , 
        thread_pool.append(t)


def Thread_Start(arg):
    """A function that represents a thread of control.
      And by calling them instantiations ,that produced from 
      'threading.Thread', from list thread_pool ,
      And block the main thread  
    """
    for i in range(arg):
        thread_pool[i].start()
    for i in range(arg):
        thread_pool[i].join()


def main():
    '''A function of main'''
    _lock = threading.RLock()
    # 
    print "process start at: ".upper(), ctime()
    Thread_Pool(loop, _max_link,_lock)
    Thread_Start(_max_link)
    print "process end at: ".upper(), ctime(),"now count :",count


if __name__ == '__main__':
    main()

실행 결과:
PROCESS START AT:  Fri Apr 28 16:52:13 2017
start loop 0 at:  Fri Apr 28 16:52:13 2017
start loop 1 at:  Fri Apr 28 16:52:13 2017
start loop 2 at:  Fri Apr 28 16:52:13 2017
start loop 3 at:  Fri Apr 28 16:52:13 2017
start loop 4 at:  Fri Apr 28 16:52:13 2017
start loop 5 at:  Fri Apr 28 16:52:13 2017
start loop 6 at:  Fri Apr 28 16:52:13 2017
start loop 7 at:  Fri Apr 28 16:52:13 2017
start loop 8 at:  Fri Apr 28 16:52:13 2017
start loop 9 at:  Fri Apr 28 16:52:13 2017
end loop 0 at: end loop 1 at: end loop 2 at:    Fri Apr 28 16:52:15 2017Fri Apr 28 16:52:15 2017Fri Apr 28 16:52:15 2017


end loop 6 at: end loop 3 at: end loop 5 at: end loop 4 at:     Fri Apr 28 16:52:15 2017Fri Apr 28 16:52:15 2017Fri Apr 28 16:52:15 2017Fri Apr 28 16:52:15 2017



end loop 8 at: end loop 7 at:  end loop 9 at:  Fri Apr 28 16:52:15 2017 Fri Apr 28 16:52:15 2017
Fri Apr 28 16:52:15 2017

PROCESS END AT:  Fri Apr 28 16:52:15 2017 now count : 10

Semaphore 방법 및 BoundedSemaphore 방법 정보


Semaphore는 계수를 가진 루틴 동기화 메커니즘으로release를 호출할 때 계산을 늘리고acquire를 호출할 때 계수를 줄이며 계수가 0일 때 자동으로 막혀release가 호출되기를 기다린다.파이톤에는 두 종류의 Semphore가 존재한다. 하나는 순수한 Semphore이고, 또 하나는 Bounded Semaphore이다.
Semphore:release () 함수를 호출할 때, 증가한 계수가 상한선을 초과했는지 확인하지 않습니다. (상한선이 없으면 계속 상승합니다) BoundedSemaphore:release () 함수를 호출할 때, 증가한 계수가 상한선을 초과했는지 확인합니다. 그러면 사용한 계수가 보장됩니다.

인스턴스 4:


Semaphore 메서드 정보
#_*_coding:utf-8_*_
import threading
from time import sleep, ctime



_max_link = 100
# A pool of thread max-link
thread_pool = []
# A list for saving instantiations of thread
lock_pool = []
# A list for saving instantiation of Lock
count = 0
# A global var


def loop(*args):
    """A function for sleep sometime s ,and make global count ++"""
    _index,_lock_Semaphore = args
    print "start loop %s at: " % _index, ctime()
    _lock_Semaphore.acquire()
    sleep(1)
    global count
    count += 1
    _lock_Semaphore.release()
    sleep(2)
    print "end loop %s at: " % _index, ctime()


def Thread_Pool(*arg):
    """A function that create instantiations of threading"""
    _func, _LN ,_Lock= arg
    for i in range(_LN):
        t = threading.Thread(target=_func, args=(i,_Lock))
        thread_pool.append(t)


def Thread_Start(arg):
    """A function that represents a thread of control.
      And by calling them instantiations ,that produced from 
      'threading.Thread', from list thread_pool ,
      And block the main thread  
    """
    for i in range(arg):
        thread_pool[i].start()
    for i in range(arg):
        thread_pool[i].join()


def main():
    '''A function of main'''
    _Semaphore = threading.Semaphore(3)
    print "process start at: ".upper(), ctime()
    Thread_Pool(loop, _max_link,_Semaphore)
    Thread_Start(_max_link)
    print "process end at: ".upper(), ctime(),"now count :",count


if __name__ == '__main__':
main()

인스턴스 5:


BoundedSemaphore
#_*_coding:utf-8_*_
import threading
from time import sleep, ctime

_max_link = 100
# A pool of thread max-link
thread_pool = []
# A list for saving instantiations of thread
lock_pool = []
# A list for saving instantiation of Lock
count = 0
# A global var


def loop(*args):
    """A function for sleep sometime s ,and make global count ++"""
    _index,_lock_Semaphore = args
    print "start loop %s at: " % _index, ctime()
    _lock_Semaphore.acquire()
    sleep(1)
    global count
    count += 1
    _lock_Semaphore.release()
    sleep(2)
    print "end loop %s at: " % _index, ctime()


def Thread_Pool(*arg):
    """A function that create instantiations of threading"""
    _func, _LN ,_Lock= arg
    for i in range(_LN):
        t = threading.Thread(target=_func, args=(i,_Lock))
        thread_pool.append(t)


def Thread_Start(arg):
    """A function that represents a thread of control.
      And by calling them instantiations ,that produced from 
      'threading.Thread', from list thread_pool ,
      And block the main thread  
    """
    for i in range(arg):
        thread_pool[i].start()
    for i in range(arg):
        thread_pool[i].join()


def main():
    '''A function of main'''
    _Semaphore = threading.BoundedSemaphore(3)
    print "process start at: ".upper(), ctime()
    Thread_Pool(loop, _max_link,_Semaphore)
    Thread_Start(_max_link)
    print "process end at: ".upper(), ctime(),"now count :",count


if __name__ == '__main__':
    main()

좋은 웹페이지 즐겨찾기