상세 컨텐츠

본문 제목

파이썬) 9. 쓰레드

파이썬

by 37_KIM 2022. 7. 20. 21:20

본문

 

 

9.Thread -쓰레드

 

- 프로그램이 실행됐을 때 작업을 수행하는 단위 일반적으로 하나의 프로그램은 하나의 스레드를 가지고 있다. 따라서 한번에 하나의 코드만 실행 가능하다.

하지만 둘 이상의 스레드를 동시에 실행 할 수도 있다.

파이썬에서는 함수를 만들고 함수를 스레드 모듈로 실행시키면 해당 함수는 하나의 쓰레드로 동작한다

(1) threading 모듈

import threading

 

(2)쓰레드 만들기

def 함수이름():

    print('func1')

thread1 = threading.Thread(target=함수이름) ※여기서 함수이름옆 괄호붙이지 않는다

thread1.start()

서버 쓰레드

 

->입력창

import threading  # 모듈생성

# 1부터 10까지 출력하면서 더한 결과를 출력하는 함수
def func1():
    total = 0
    for i in range(1,101,1):
        total = total + i
        print("함수 1번 i : ", i)
        print("함수 1번 total : ", total)

# 10부터 1까지 출력하면서 더한 결과를 출력하는 함수
def func2():
    total = 0
    for i in range(10,0,-1):
        total = total + i
        print("함수 2번 i : ", i)
        print("함수 2번 total : ", total)

t1 = threading.Thread(target=func1)
t2 = threading.Thread(target=func2)

t1.start()
t2.start()

 

->출력창

C:\Users\slinfo\PycharmProjects\day05\venv\Scripts\python.exe C:/Users/slinfo/PycharmProjects/day05/ex01.py
함수 1번 i :  1
함수 1번 total :  1
함수 1번 i :  2
함수 1번 total :  3
함수 1번 i :  3
함수 1번 total :  6
함수 1번 i :  4
함수 1번 total :  10
함수 1번 i :  5
함수 1번 total :  15
함수 1번 i :  6함수 2번 i :  10
함수 2번 total :  
함수 1번 total :  2110
함수 2번 i :  9
함수 2번 total :  
함수 1번 i :  719
함수 2번 i : 
함수 1번 total :  28
 8함수 1번 i :  8
함수 2번 total :  27
함수 2번 i :  
함수 1번 total :  7
함수 2번 total :  34
함수 2번 i :  636
함수 1번 i : 
함수 2번 total :  9
함수 1번 total :   40
함수 2번 i :  45
함수 1번 i :  10
함수 1번 total : 5
함수 2번 total :  55
 45
함수 2번 i :  4
함수 2번 total :  49
함수 2번 i :  3
함수 2번 total :  52
함수 2번 i :  2
함수 2번 total :  54
함수 2번 i :  1
함수 2번 total :  55

Process finished with exit code 0

 

 

 

-------------

클라이언트 쓰레드

 

->입력창

import socket	# 네트워크 입출력(하드웨어 장치와의 통로)
import threading

host = '127.0.0.1'  # IP주소
port = 9999         # 포트 번호

# 서버 소켓(랜 카드와의 통로) 생성, 사용할 프로토콜 IPv4, TCP
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 서버 소켓 통로에 IP주소와 포트번호 설정
server_socket.bind((host, port))
# 서버의 상태를 listen(클라이언트 접속 대기)로 변경
server_socket.listen(0)
# 클라이언트가 접속하면 해당 접속을 허용
client_socket, addr = server_socket.accept()

def recv_func():
    while True:
        recv_data = client_socket.recv(65535)
        print(recv_data.decode('utf-8'))

def send_func():
    while True:
        send_data = input()
        client_socket.send(send_data.encode('utf-8'))

recv_thread = threading.Thread(target=recv_func)
send_thread = threading.Thread(target=send_func)
recv_thread.start()
send_thread.start()

while True:
    pass

client_socket.close()
server_socket.close()

'파이썬' 카테고리의 다른 글

파이썬) 10. 객체 지향 프로그래밍  (0) 2022.07.20
파이썬) 8. 네트워크  (0) 2022.07.20
파이썬) 7. 모듈  (0) 2022.07.20
파이썬) 6. 함수 응용Q  (0) 2022.07.20
파이썬) 6. 함수  (0) 2022.07.20

관련글 더보기