스레드 (1)

  • 개념 정의
  • 파이썬 스레드
  • 데몬 스레드
  • fork, join

 

개념 정의

  • 운영체제는 동시에 실행되는 여러 프로그램들을 잘 관리해야한느데 이런 작업을 스케줄링 이라함
  • 스케줄의 단위는 스레드인데, 프로그램은 여러개의 스레드를 사용할 수 있는데, 이를 멀티 스레드라고 함
  •  스레드
    • 프로세스의 실행 단위
  • 프로세스 
    • 프로그램이 메모리에 올라가서 실행 중인 것을 말함

 

 

파이썬 스레드

  • thread, threading 모듈이 있음 <-- threding 모듈을 더 많이 사용함
  • GUI 라이브러리인 QThread 도 있음
  • run 메소드
    • start 함수 실행하면 클래스 안에 run 함수가 호출됨
  • start 메소드
    • 쓰레드 실행하는 함수
  • join 메소드
    • 쓰레드가 종료될 때까지 대기함
import threading
import time


# thread 직접 사용
def t_Thread(num1, num2):
    for i in range(5):
        print(f'thread : {i}')
        time.sleep(1)

t = threading.Thread(target=t_Thread, args=(1, 10))   # target=thread func name, args=(num1, num2)
t.start()
print('Main Thread')



# class 사용
class Worker(threading.Thread):
    def __init__(self, num):
        super().__init__()
        self.num = num        

    def run(self):  
        for i in range(self.num):
            print(f'sub thread start {i}\n')
            time.sleep(1)



if __name__ == '__main__':

    print('main thread start')    

    t = Worker(5)                        # thread 생성
    t.daemon = True                     # 데몬 스레드 실행 --> 프
    t.start()                           # sub thread run() 호출됨

    print('main thread end ')

 

 

데몬 스레드

  • 데몬 속성 - 서브 쓰레드가 데몬 쓰레드인지 아닌지를 지정하는 것 (디폴트 False)
  • 데몬 스레드 - 백그라운드에서 실행되는 스레드로 메인 쓰레드가 종료되면 즉시 종료되는 스레드
  • 데몬 스레드가 아니면 해당 서브 쓰레드는 메인 스레드가 종료되도 자기 작업이 끝날때까지 지속됨
  • GUI 라이브러리인 QThread 도 있음
# 데몬 스레드(daemon thread)

import threading
import time

def count(num, t, thread_num):
    print(f'thread {thread_num} start')
    
    for i in range(num):
        print(f'thread {thread_num} running {i}')
        time.sleep(t)
    
    print(f'thread {thread_num} ends')

thread_1 = threading.Thread(target=count, args=(10, 0.5, 1))
thread_1.daemon = True  # default : False
thread_1.start()

count(5, 0.5, 2)

 

 

Fork, Join 함수

  • Fork
    • 메인 스레드가 서브 스레드를 생성하는 것
    • 두개의 서브 스레드를 생성하는 경우, 메인스레드를 포함하여 총 3개의 스레드가 스케줄링 됨
  • Join
    • join 은 모든 스레드가 작업을 마칠때 까지 기다리는 것을 의미함. 
    • 데이터를 여러 스레드를 통해서 별렬로 처리한 후 그 값들을 다시 모아서 순차적으로 처리해야 할 필요가 있을때, 분할한 데이터가 모든 스레드에서  처리 될 때까지 기다렸다가 메인 스레드가 다시 추후 작업을 하는 경우에 사용
    • 부모 스레드, 즉, 해당 스레드를 생성한 스레드를 진행하지 않고, 자식 스레드 즉 새로 생성한 스레드의 종료를 기다려 준다는 의미
    • 스레드가 끝날때 까지 기다려 주는 함수

import threading
import time


class Worker(threading.Thread):
    def __init__(self, name):
        super().__init__()
        self.name = name    # thread 이름 지정
        
    def run(self):
        print('sub thread start', threading.current_thread().getName())
        time.sleep(5)
        print('sub thread start', threading.current_thread().getName())
        


print('main thread start')

t1 = Worker('1')    # sub thread 생성
t1.start()          # sub thread run method 호출

t2 = Worker('2')    # sub thread 생성
t2.start()          # sub thread run method 호출

t1.join()
t2.join()

print('main thread post job')
print('main thread end')


"""
# thread 여러개 생성
print('main thread start')

threads = []
for i in range(3):
	thread = Worker(i)
    thread.start()
    threads.append(thread)
    

for thread in threads:
	thread.join()

print('main thread post job')
print('main thread end')

"""

 

 

 

reference

 

02) 파이썬 스레드

[TOC] ## 프로세스와 스레드 운영체제에서 어떤 실행 프로그램이 실행된다는 것은 CPU, 메모리, SSD와 같은 컴퓨터 자원을 사용합니다. 따라서 운영체체제는 프로그램들이…

wikidocs.net

 

Python Thread 예제

파이썬에서 스레드를 사용하는 방법을 다루고 있습니다. 1. 쓰레드 (Thread) 2. 스레드 생성 및 실행 3. join 함수 4. 데몬 쓰레드 5. Concurrent.futures 모듈 6. 전역 변수 공유 7. GIL(Global Interpreter Lock) 8. 프

webnautes.tistory.com

 

 

[edu] thread start/join (스레드 시작, 조인, start, join)

프로그램을 작성하다 보면 동시성이 필요하게 될때가 있다. 즉 여러가지 일을 동시에 진행해야 한다. os 에서 프로세스마다 리소스를 할당해서 여러 프로세스가 동시에 실행되는데 하나의 프로

burningrizen.tistory.com

 

'Python' 카테고리의 다른 글

[ Thread ] 스레드 (3) - Lock()  (0) 2022.12.16
[ Thread ] 스레드 (2) - 멀티 스레드  (0) 2022.12.15
[Socket] 소켓(Socket) 프로그래밍 (1)  (1) 2022.09.21
[Python] enumerate 함수  (0) 2022.01.26
[Python] Zip 함수  (0) 2022.01.26

딕셔너리

  • 리스트와 같이 값 변경, 추가 가능
  • 별 표현식
    • 데이터 언패킹은 데이터 개수가 같아야 하지만 star expression 을 사용하면 변수의 개수가 달라도 언패킹이 가능함

 

딕셔너리 생성
# 딕셔너리 생성

# 빈 딕셔너리 생성
dict = {}

# 생성
data = {'d1' : 1,
        'd2' : 2,
        'd3' : 3}
        
# 추가
data['d4'] = 4


# get data --> key 값으로 가져옴
print(data['d2'])		# 2


# 값 변경
data['d2'] = 4
print(data['d2'])		# 4


# 값 삭제
del data['d2']
print(data)		#


# value 여러개
data = {'d1' : [1, 10],
        'd2' : [2, 20],
        'd3' : [3, 30]}
        
 
 # 인덱싱
 print(data['d1'][0])	# 1
 print(data['d1'][1])	# 10
 
 
  # 딕셔너리 추가
 print(data['d1'][0])	# 1
 print(data['d1'][1])	# 10

 

 

 

keys 메서드, values 메서드,   update 메서드,  zip과 dict
  • keys     -   key 값만 가져옴
  • values   -   value 값만 가져옴
  • zip    - key, value 쌍을 묶어줌
data = {'d1', 1, 'd2', 2, 'd3', 3, 'd4', 4}

# keys
key = list(data.keys())		# [d1, d2, d3, d4]


# values
values = list(data.values())	# [1, 2, 3, 4]


# update
data2 = {'d5', 5, 'd6', 6}

data2.update(data)
print(data2)		# {'d1', 1, 'd2', 2, 'd3', 3, 'd4', 4, 'd5', 5, 'd6', 6}



# zip
keys = {'t1', 't2', 't3'}
vals = {100, 200, 300}
print(zip(keys, vals))		# zip 형태로 출력됨
print(dict(zip(keys, vals)))		# dictionary 형태로 형변환 해줌

'Python Tutorial' 카테고리의 다른 글

[ Python Tutorial ] 클래스  (0) 2022.12.26
[ Python Tutorial ] 튜플  (1) 2022.12.10
[ Python Tutorial ] 리스트  (0) 2022.12.09
[ Python Tutorial ] 문자열  (0) 2022.12.08
[ Python Tutorial ] Print 출력  (0) 2022.12.07

튜플

  • 리스트 - 순서가 있으며 수정 가능
  • 튜플 - 순서가 있으나 수정 불가능

 

튜플 생성
# 튜플 생성

test1 = ('d1', 'd2', 'd3)
print(test1) 	# ('d1', 'd2', 'd3')

# 괄호 없이 생성 가능
test1 = 1, 2, 3
print(test1) 	# ('d1', 'd2', 'd3')

# 한개만 생성 시
test2 = ('1', )		# test2 = ('1') 으로 생성하면 integer 가 됨
print(test2)		# ('1')

 

 

 

range 함수
  • 범위를 지정하는 함수
# range 함수

data = tuple(range(2, 100, 2)
print(data)			# (2, 4, 6, 8, 10, ... 100)

 

 

'Python Tutorial' 카테고리의 다른 글

[ Python Tutorial ] 클래스  (0) 2022.12.26
[ Python Tutorial ] 딕셔너리  (0) 2022.12.12
[ Python Tutorial ] 리스트  (0) 2022.12.09
[ Python Tutorial ] 문자열  (0) 2022.12.08
[ Python Tutorial ] Print 출력  (0) 2022.12.07

리스트

  • 문자열과 달리 수정이 가능함
  • 리스트끼리의 덧셈 연산을 하면 모든 원소들이 합쳐짐

 

append,   insert 
  • append   -  리스트에 원소 추가 메서드. 맨 뒤에 추가
  • insert    -   리스트 원하는 위치에 원소 추가
data = [1,2,3,4,5]

# append
data.append(6)
print(data)		# [1,2,3,4,5,6]


# insert - (원소 위치, data)
data.insert(1, 0)
print(data)		# [1,0,2,3,4,5,6]

 

del
  • 리스트 원소 삭제
# del

data = [1,2,3,4,5]
del data[2]
print(data)		# [1,2,4,5]

 

join
  • 매개변수로 들어온 리스트에 있는 요소 하나하나를 합쳐서 하나의 문자열로 바꾸어 반환하는 함수
# join

data = ['a', 'b', 'c', 'd']


# 구분자 " " 
str = " ".join(data)	
print(str)		# a b c d

# 구분자 "." 
str = ".".join(data)	
print(str)		# a.b.c.d

 

 

sort, sorted
  • 리스트를 오름차순으로 정렬
  • sort   - 원본 리스트 변경하여 정렬
  • sorted   - 원본 리스트는 변경 없이 정렬
# sort

data = [2,3,5,1,4,9]

# sort
data.sort()
print(data)		# [1,2,3,4,5,9]


# sorted
data2 = sorted(data)
print(data2)	# [1,2,3,4,5,9]

'Python Tutorial' 카테고리의 다른 글

[ Python Tutorial ] 클래스  (0) 2022.12.26
[ Python Tutorial ] 딕셔너리  (0) 2022.12.12
[ Python Tutorial ] 튜플  (1) 2022.12.10
[ Python Tutorial ] 문자열  (0) 2022.12.08
[ Python Tutorial ] Print 출력  (0) 2022.12.07

문자열

  • 문자열의 경우, 생성되면 변경 불가 
string = 'hello'

# 변경 안됨
string.replace('h', 'H')	

# 변경 가능. 다시 binding 해줘야함
string = string.replace('h', 'H')

 

 

문자열 인덱싱(indexing)

 

# indexing
str = hello

# 첫번째 문자
print(str[0])

# 세번째 문자
print(str[2])

# 마지막 문자
print(str[-1])

# 마지막 문자만 빼고
print(str[:-1])

 

문자열 슬라이싱(slicing)

string [start:end:step]   

str = hello world

# 전체 출력
print(str)

# world 출력
print(str[6:10])
print(str[6:])
print(str[-5:])

# slicing [start : end : step]
print(str[::2])
print(str[1::2])
print(str[:4:2])

# 문자열 뒤집기
print(str[::-1])

 

replace 함수 - 문자열 변환
string = '111,222,333,444'

# , 를 - 으로 변경
string1 = string.replace(',', '-')
print(string1)

 

split함수 - 문자열 자르기
str = '111.222.333.444'

# 333
print(str.split('.')[2])

# 444
print(str.split('.')[-1])

 

 

문자열 연산
# 문자열 더하기
a = '1'
b = '2'
print(a + b)	# 12

# 문자열 곱하기
print('hello' * 3)	# hellohellohello

 

 

strip 함수 - 공백 제거 함수
str = ' 11 22 33 44 55'


# 공백 제거
str = str.strip()
print(str)			# 1122334455

 

 

upper, lower, capitalize 메서드
  • upper  - 대문자로 변경
  • lower   - 소문자로 변경
  • capitalize   -  앞글자만 대문자로 변경
# upper

str = 'hello'
str = str.upper()
print(str)		# HELLO


# lower

str = 'HELLO'
str = str.lower()
print(str)		# hello


# capitalize

str = 'hello'
str = str.capitalize()
print(str)		# Hello

 

 

endswith, startswith
  • endswith   -   파일명의 확장자를 확인하는 메서드
  • startswith  -   파일 시작을 비교하는 메서드
# endswith

file = 'test.xlsx'
print(file.endswith('xlsx'))	# True return


# startswith

file = 'test11.xlsx'
print(file.startswith('test11'))	# True return

 

 

 

split
  • 문자열을 자르는 함수 
# spllit

data = '11-22-33-44'
print(data.split('-'))	# ['11', '22', '33', '44']	list 형태로 반환

 

 

 

'Python Tutorial' 카테고리의 다른 글

[ Python Tutorial ] 클래스  (0) 2022.12.26
[ Python Tutorial ] 딕셔너리  (0) 2022.12.12
[ Python Tutorial ] 튜플  (1) 2022.12.10
[ Python Tutorial ] 리스트  (0) 2022.12.09
[ Python Tutorial ] Print 출력  (0) 2022.12.07

Print 출력 

 

"sep = "  : 여러개 문자들을 구분하여 출력하는 법 
# test_1 test_2 test_3 출력
print('test_1 ', 'test_2 ', 'test_3 ')

# test_1;test_2;test_3 출력
print('test_1', 'test_2', 'test_3', sep=';')

 

"end= "  : print 함수의 경우, \n 자동 줄바꿈이 디폴트로 되어있음. end=" " 설정 시, 줄바꿈 없음
# 자동 줄바꿈
print('test_1')
print('test_2')

# 줄바꿈 없이 출력
print('test_1', end="")
print('test_2', end="")

 

 

한줄에 여러개의 코드를 작성하고 싶을때, ; (세미콜론을) 붙여서 한줄에 써줌
# 한줄에 한명령어
print('test_1')
print('test_2')


# 한줄에 여러 명령어 사용시, 
print('test_1'); print('test_2')

 

 

format 
# format 사용

name = 'lee'
age = 20

print('my name is {} and age is {}'.format(name, age))

'Python Tutorial' 카테고리의 다른 글

[ Python Tutorial ] 클래스  (0) 2022.12.26
[ Python Tutorial ] 딕셔너리  (0) 2022.12.12
[ Python Tutorial ] 튜플  (1) 2022.12.10
[ Python Tutorial ] 리스트  (0) 2022.12.09
[ Python Tutorial ] 문자열  (0) 2022.12.08

[Socket] 소켓(Socket) 프로그래밍 (1)

 - 소켓 프로그래밍 개요

 - 구조체 파일 전송 방법 - Struct

    . Big Endian vs Little Endian

 - 프로토콜 설계

 

 

 

 

소켓(Socket) 프로그래밍 개요

 - 다른 디바이간 데이터를 주고받기 위한 프로그래밍.

 - 네트워크 프로그래밍

 - TCP/IP 소켓 프로그래밍 개념도

TCP/IP 소켓 프로그래밍 개념

 - 자세한 내용은 아래 블로그 참조

https://velog.io/@devsh/%EB%84%A4%ED%8A%B8%EC%9B%8C%ED%81%AC-%EA%B8%B0%EC%B4%88-%EA%B0%9C%EB%85%90-%EC%A0%95%EB%A6%AC%ED%95%98%EA%B8%B0-%EC%86%8C%EC%BC%93%EA%B3%BC-%EC%86%8C%EC%BC%93-%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D-%EA%B0%9C%EB%85%90

 

네트워크 기초 개념 정리하기 - 소켓과 소켓 프로그래밍 개념

소켓은 사전적인 의미로 구멍, 연결, 콘센트등의 의미한다.. 이와 마찬가지로 네트워크 프로그래밍 관전에서도 소켓의 의미는 프로그램이 네트워크에서 데이터를 송수신할 수 있도록 "네트워크

velog.io

 

 

 

 

구조체 파일 전송 방법 - Struct 

 - 샘플 코드가 아닌 실제 데이터 전송을 위해서는 구조체 형태의 파일이 일반적임.

 - 파이썬에서 구조체 형태로 변형을 위해서 struct 모듈 제공. 

 - 이외에도 pickle, shelve 등이 있음 <-- 추후 스터디.

 - 아래 그림은 struct 모듈에서 제공하는 포맷 스트링

 - 자세한 내용은 아래 참조 

https://docs.python.org/3/library/struct.html

 

struct — Interpret bytes as packed binary data — Python 3.10.7 documentation

struct — Interpret bytes as packed binary data Source code: Lib/struct.py This module performs conversions between Python values and C structs represented as Python bytes objects. This can be used in handling binary data stored in files or from network c

docs.python.org

 

 

- pack, unpack, calcsize

  • pack
    • 여러가지 타입의 데이터들을 구조체 형식으로 변환
  • unpack
    • pack 된 데이터를 튜플로 반환
  • calcsize
    • 파이썬 문자열이 요구하는 바이트 반환

 

 

 

 

Big Endian vs Little Endian

 - 바이트 배치 순서에 따라 big endian, little endian 으로 구분됨

 - 구조체 형태로 pack 할때, big endian, little endian 구분해서 할 수 있음.

 - 서로 다른 기기에 맞춰서 셋팅해줘야함.

 

 - 자세한 설명은 아래 참조

https://jhnyang.tistory.com/172

 

[Byte Order 바이트 오더] 빅엔디안(Big Endian)과 리틀엔디안(little endian) - 1편

안녕하세요~~!! 오늘도 시작되는 말랑이몰랑이 블로그 포스팅입니다~ ㅎㅎ 오늘은 네트워크나 통신쪽을 공부한다면 알고 있어야 할 Byte Order 의 빅엔디안과 리틀엔디안에 대한 개념을 완전하게

jhnyang.tistory.com

 

 

 

 

 

- sample code - pack, unpack, calcsize

    # pack 
    pack_1 = pack('!hhl', 1, 2, 3)
    print(f'pack_1 : {pack("!hhl", 1, 2, 3)}')
    
    # unpack
    unpack_1 = unpack('!hhl', pack_1)
    print(f'unpack_1 : {unpack_1}')
    
    # calsize
    print(f'size : !hhl : {calcsize("!hhl")}')
    
    
    # pack
    pack_2 = pack('>3h', 1, 2, 3)
    print(f'pakc_2 : {pack(">3h", 1, 2, 3)}')
    
    # unpack
    unpack_2 = unpack('>3h', pack_2)
    print(f'unpack_2 : {unpack_2}')
    
    
    
    # pack
    pack_3 = pack('<6s', bytes("hello", "utf-8"))
    print(pack('<6s', bytes("hello", "utf-8")))
    
    # unpack
    unpack_3 = unpack('<6s', pack_3)
    print(unpack_3)
    
    
    
    
    print(f'Done..')

 

 

 

Reference 

https://plummmm.tistory.com/176

 

파이썬 struct 모듈 (pack, unpack)

 파이썬 자료형과 c언어 구조체형 사이에서 데이터 변환을 할 때 사용하는 것이다. 이 친구들은 당연히 import struct 를 해줘야 사용이 가능하지. C 프로그램이 파일에 저장한 바이너리 정보들을

plummmm.tistory.com

 

 

 

'Python' 카테고리의 다른 글

[ Thread ] 스레드 (2) - 멀티 스레드  (0) 2022.12.15
[ Thread ] 스레드 (1)  (0) 2022.12.14
[Python] enumerate 함수  (0) 2022.01.26
[Python] Zip 함수  (0) 2022.01.26
[Python] lambda (람다 함수), map 함수, reduce 함수  (0) 2022.01.25

[Git & GitHub (5)] GitHub Desktop 설치

 

 

GitHub Desktop 을 사용 전 준비 사항

 

  1. Git 설치
  2. VS code 설치
  3. GitHub 가입
  4. GitHub desktop 설치 ( ubuntu 설치 방법)
    • 깃허브 데스크탑은 윈도우, 맥 환경에 대해서만 제공
    • 아래 명령어 실행하여 설치 
$ sudo apt-get update
$ sudo apt-get install snapd
$ wget https://github.com/shiftkey/desktop/releases/download/release-2.0.4-linux1/GitHubDesktop-linux-2.0.4-linux1.snap
$ sudo snap install GitHubDesktop-linux-2.0.4-linux1.snap --classic --dangerous
  •  

    • 우분투 명령어 창에서 GitHub Desktop 검색하여 실행하면 아래와 같이 실행 됨.

 

 

 

 

GitHub - shiftkey/desktop: Fork of GitHub Desktop to support various Linux distributions

Fork of GitHub Desktop to support various Linux distributions - GitHub - shiftkey/desktop: Fork of GitHub Desktop to support various Linux distributions

github.com

 

+ Recent posts