Skip to main content
Skip table of contents

통합 예제 - Thread

예제를 통한 쓰레드 사용법을 설명합니다

예제 1 : 쓰레드 예제

PY
#----- thread 1: client comm. ---------------------
def fn_th_client(): 
global g_sock
global g_cmd 
res, rx_data = client_socket_read(g_sock)
if res > 0:
g_cmd = rx_data.decode() #decode: byte형을 string으로 변환 
else: # 통신에러가 발생한 경우
client_socket_close(g_sock)
exit() #프로그램 종료 
wait(0.1) 
return 0

#----- thread 2: check IO -------------------------
def fn_th_check_io():
if get_digital_input(1) == ON: 
exit() #프로그램 종료 
wait(0.1)
return 0

#----- main ---------------------------------------
g_sock = client_socket_open("192.168.137.2", 20002) #서버에 접속 
g_cmd = "" 

g_th_id1 = thread_run(fn_th_client, loop=True) # th_client 쓰레드 실행
g_th_id2 = thread_run(fn_th_check_io, loop=True) # th_check_io 쓰레드 실행

p1 = posj(0, 0, 90, 0, 90, 0)
p2 = posj(10, 0, 90, 0, 90, 0) 
p3 = posj(20, 0, 90, 0, 90, 0)

while 1: 
if g_cmd == "a":
g_cmd = "" 
movej(p1,vel=100,acc=100)
client_socket_write(g_sock, b"end") 
if g_cmd == "b": 
g_cmd = "" 
movej(p2,vel=100,acc=100)
client_socket_write(g_sock, b"end") 
if g_cmd == "c": 
g_cmd = "" 
movej(p3,vel=100,acc=100)
client_socket_write(g_sock, b"end") 
wait(0.1) 

th_client 쓰레드: server로부터 수신한 데이터를 string형으로 변하여 g_cmd에 저장

th_check_io 쓰레드: 1번 접점의 상태를 체크하여 ON 이면 프로그램 종료

main : 서버에 접속,

  1. 2개의 쓰레드 실행 : th_client, th_check_io
  2. 서버로부터 “a”가 수신되면 p1으로 이동 후, 서버에게 “end” 전송
  3. 서버로부터 “b”가 수신되면 p2으로 이동 후, 서버에게 “end” 전송
  4. 서버로부터 “c”가 수신되면 p3으로 이동 후, 서버에게 “end” 전송
JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.