Python 스레드화에 join()을 사용하는 이유는 무엇입니까?
나는 비단뱀의 실타래를 연구하다가.
'데몬 모드'를 해야 .join()
그러면 메인 스레드가 종료되기 전에 스레드가 자동으로 종료됩니다.
하지만 나는 또한 그가 이 약을 사용하는 것을t.join()
t
않았다daemon
코드 예시는 다음과 같습니다.
import threading
import time
import logging
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-10s) %(message)s',
)
def daemon():
logging.debug('Starting')
time.sleep(2)
logging.debug('Exiting')
d = threading.Thread(name='daemon', target=daemon)
d.setDaemon(True)
def non_daemon():
logging.debug('Starting')
logging.debug('Exiting')
t = threading.Thread(name='non-daemon', target=non_daemon)
d.start()
t.start()
d.join()
t.join()
t.join()
ASCII: The 。join()
아마 메인보드에 의해 호출되었을 겁니다.다른 스레드로 호출할 수도 있지만, 불필요하게 그림을 복잡하게 만들 수 있습니다.
join
콜은 메인 스레드 트랙에 배치해야 하지만 스레드 관계를 표현하고 최대한 단순하게 유지하기 위해 대신 자스레드에 배치하기로 했습니다.
without join:
+---+---+------------------ main-thread
| |
| +........... child-thread(short)
+.................................. child-thread(long)
with join
+---+---+------------------***********+### main-thread
| | |
| +...........join() | child-thread(short)
+......................join()...... child-thread(long)
with join and daemon thread
+-+--+---+------------------***********+### parent-thread
| | | |
| | +...........join() | child-thread(short)
| +......................join()...... child-thread(long)
+,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, child-thread(long + daemonized)
'-' main-thread/parent-thread/main-program execution
'.' child-thread execution
'#' optional parent-thread execution after join()-blocked parent-thread could
continue
'*' main-thread 'sleeping' in join-method, waiting for child-thread to finish
',' daemonized thread - 'ignores' lifetime of other threads;
terminates when main-programs exits; is normally meant for
join-independent tasks
변화가 않는 는 메인 가 자신의 메인 스레드 뒤에 않기 입니다.join
하면 join
는 메인 패킷의 실행 흐름과 관련이 있습니다(만.
예를 들어 여러 페이지를 동시에 다운로드하여 하나의 큰 페이지로 연결하려는 경우 스레드를 사용하여 동시 다운로드를 시작할 수 있지만 여러 페이지 중 하나의 페이지를 조립하기 전에 마지막 페이지/스레드가 완료될 때까지 기다려야 합니다.'어울리다'를 합니다.join()
.
의사로부터 직접 입수
참가하다[참가하다]스레드가 종료될 때까지 기다립니다.이것에 의해, join() 메서드가 호출되고 있는 스레드가 통상의 예외 또는 처리되지 않은 예외에 의해서 종료될 때까지, 또는 옵션의 타임 아웃이 발생할 때까지, 발신측의 스레드가 차단됩니다.
은, 「」를 하는 가,t
★★★★★★★★★★★★★★★★★」d
, 기다리다, 기다리다, 기다리다t
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
프로그램에서 사용하는 논리에 따라서는 메인 스레드를 계속하기 전에 스레드가 완료될 때까지 기다리는 것이 좋습니다.
또한 문서:
스레드는 "데몬 스레드"로 플래그가 지정될 수 있습니다.이 플래그의 중요성은 데몬 스레드만 남아 있으면 Python 프로그램 전체가 종료된다는 것입니다.
예를 들어 다음과 같습니다.
def non_daemon():
time.sleep(5)
print 'Test non-daemon'
t = threading.Thread(name='non-daemon', target=non_daemon)
t.start()
마지막은 다음과 같습니다.
print 'Test one'
t.join()
print 'Test two'
다음과 같이 출력됩니다.
Test one
Test non-daemon
Test two
합니다.t
call " " " " " 가 호출될 때까지 됩니다.print
두 번째에요.
또는 다음과 같은 기능이 있는 경우:
print 'Test one'
print 'Test two'
t.join()
다음과 같은 출력이 표시됩니다.
Test one
Test two
Test non-daemon
스레드에서 하고 그 후 를.t
이 결합을 제거할 .t.join()
하게 됩니다.t
완성할 수 있습니다.
이 스레드 고마워요.저도 큰 도움이 됐어요
오늘 .join()에 대해 배웠습니다.
다음 스레드는 병렬로 실행됩니다.
d.start()
t.start()
d.join()
t.join()
(원하는 것이 아니라) 순차적으로 실행됩니다.
d.start()
d.join()
t.start()
t.join()
특히, 저는 똑똑하고 깔끔하게 하려고 노력했습니다.
class Kiki(threading.Thread):
def __init__(self, time):
super(Kiki, self).__init__()
self.time = time
self.start()
self.join()
이거 돼!하지만 그것은 순차적으로 실행된다.self.start()는 __init__에 넣을 수 있지만 self.join()은 넣을 수 없습니다.모든 스레드가 시작된 후에 수행해야 합니다.
join()은 메인 스레드가 스레드가 완료될 때까지 대기하는 원인입니다.그렇지 않으면 스레드가 자동으로 실행됩니다.
따라서 join()을 메인 스레드의 "홀드"라고 생각하는 한 가지 방법은 메인 스레드가 속행하기 전에 스레드를 디스레드하고 메인 스레드에서 순차적으로 실행되는 것입니다.그러면 메인 스레드가 앞으로 이동하기 전에 스레드가 완료됩니다.이는 join()을 호출하기 전에 스레드가 이미 종료되어도 괜찮다는 것을 의미합니다.메인 스레드는 join()이 호출되면 바로 해제됩니다.
실제로 메인 스레드는 t.join()으로 이행하기 전에 스레드d가 종료될 때까지 d.join()에서 대기하고 있다는 생각이 방금 들었습니다.
확실히 하기 위해서, 다음의 코드를 고려해 주세요.
import threading
import time
class Kiki(threading.Thread):
def __init__(self, time):
super(Kiki, self).__init__()
self.time = time
self.start()
def run(self):
print self.time, " seconds start!"
for i in range(0,self.time):
time.sleep(1)
print "1 sec of ", self.time
print self.time, " seconds finished!"
t1 = Kiki(3)
t2 = Kiki(2)
t3 = Kiki(1)
t1.join()
print "t1.join() finished"
t2.join()
print "t2.join() finished"
t3.join()
print "t3.join() finished"
이 출력(인쇄문이 서로 어떻게 나사산되어 있는지 주의해 주세요)을 생성합니다.
$ python test_thread.py
32 seconds start! seconds start!1
seconds start!
1 sec of 1
1 sec of 1 seconds finished!
21 sec of
3
1 sec of 3
1 sec of 2
2 seconds finished!
1 sec of 3
3 seconds finished!
t1.join() finished
t2.join() finished
t3.join() finished
$
t1.join()이 메인 스레드를 지탱하고 있습니다.3개의 스레드 모두 t1.join()이 종료되기 전에 완료되며 메인 스레드는 t2.join()을 실행하고 다음으로 t3.join()을 인쇄한 후 인쇄합니다.
정정해주시면 감사하겠습니다.저도 스레딩은 처음입니다.
(주의: 관심 있는 경우 DrinkBot의 코드를 작성하고 있습니다.원료 펌프를 순차적으로 실행하는 것이 아니라 동시에 실행하는 스레드가 필요합니다.각 음료를 기다리는 시간이 단축됩니다.)
메서드 join()
는 join() 메서드가 호출된 스레드가 종료될 때까지 발신 스레드를 차단합니다.
출처 : http://docs.python.org/2/library/threading.html
가입 - 인터프리터는 프로세스가 완료되거나 종료될 때까지 기다립니다.
>>> from threading import Thread
>>> import time
>>> def sam():
... print 'started'
... time.sleep(10)
... print 'waiting for 10sec'
...
>>> t = Thread(target=sam)
>>> t.start()
started
>>> t.join() # with join interpreter will wait until your process get completed or terminated
done? # this line printed after thread execution stopped i.e after 10sec
waiting for 10sec
>>> done?
join이 없으면 인터프리터는 프로세스가 종료될 때까지 기다리지 않습니다.
>>> t = Thread(target=sam)
>>> t.start()
started
>>> print 'yes done' #without join interpreter wont wait until process get terminated
yes done
>>> waiting for 10sec
python 3.x join()에서는 메인 스레드와 스레드를 결합하기 위해 사용됩니다.즉, 특정 스레드에 join()을 사용하면 메인 스레드는 결합 스레드의 실행이 완료될 때까지 실행을 중지합니다.
#1 - Without Join():
import threading
import time
def loiter():
print('You are loitering!')
time.sleep(5)
print('You are not loitering anymore!')
t1 = threading.Thread(target = loiter)
t1.start()
print('Hey, I do not want to loiter!')
'''
Output without join()-->
You are loitering!
Hey, I do not want to loiter!
You are not loitering anymore! #After 5 seconds --> This statement will be printed
'''
#2 - With Join():
import threading
import time
def loiter():
print('You are loitering!')
time.sleep(5)
print('You are not loitering anymore!')
t1 = threading.Thread(target = loiter)
t1.start()
t1.join()
print('Hey, I do not want to loiter!')
'''
Output with join() -->
You are loitering!
You are not loitering anymore! #After 5 seconds --> This statement will be printed
Hey, I do not want to loiter!
'''
이 예에서는,.join()
액션:
import threading
import time
def threaded_worker():
for r in range(10):
print('Other: ', r)
time.sleep(2)
thread_ = threading.Timer(1, threaded_worker)
thread_.daemon = True # If the main thread is killed, this thread will be killed as well.
thread_.start()
flag = True
for i in range(10):
print('Main: ', i)
time.sleep(2)
if flag and i > 4:
print(
'''
Threaded_worker() joined to the main thread.
Now we have a sequential behavior instead of concurrency.
''')
thread_.join()
flag = False
출력:
Main: 0
Other: 0
Main: 1
Other: 1
Main: 2
Other: 2
Main: 3
Other: 3
Main: 4
Other: 4
Main: 5
Other: 5
Threaded_worker() joined to the main thread.
Now we have a sequential behavior instead of concurrency.
Other: 6
Other: 7
Other: 8
Other: 9
Main: 6
Main: 7
Main: 8
Main: 9
만들 때join(t)
비실행 스레드와 데몬 스레드 양쪽에 대한 함수는 메인 스레드(또는 메인 프로세스)가 대기해야 합니다.t
그 후, 독자적인 프로세스로 작업을 진행할 수 있습니다.의 기간 동안t
대기 시간(초)입니다. 두 개의 자식 스레드 모두 일부 텍스트를 인쇄하는 등 수행할 수 있는 작업을 수행해야 합니다.그 후t
seconds(초)는 비메인 스레드가 아직 작업을 완료하지 않은 경우, 그리고 메인 프로세스가 작업을 완료한 후에도 작업을 완료할 수 있지만 데몬 스레드의 경우 기회 창을 놓쳤을 뿐입니다.그러나 python 프로그램이 종료된 후에는 결국 죽게 됩니다.잘못된 점이 있으면 정정해 주세요.
메인 스레드(또는 다른 스레드)가 다른 스레드를 결합하는 데는 몇 가지 이유가 있습니다.
스레드에서 일부 리소스가 생성되었거나 유지(잠금)되었을 수 있습니다.가입 호출 스레드가 대신 리소스를 지울 수 있습니다.
join()은 착신측 스레드가 종료된 후에도 Join-Resign 스레드를 계속하기 위한 자연스러운 블로킹콜입니다
python 프로그램이 다른 스레드에 가입하지 않는 경우에도 python 인터프리터는 대신 non-daemon 스레드에 가입합니다.
"join()을 사용하면 무슨 소용이 있습니까?"라고 묻습니다."파일을 닫는 게 무슨 소용입니까?"와 같은 대답입니다. 왜냐하면 python과 OS는 프로그램이 종료되면 파일을 닫아버릴 것입니다.
그것은 단지 좋은 프로그래밍의 문제이다.스레드가 자신의 코드를 간섭하기 위해 실행되고 있지 않은지, 대규모 시스템에서 올바르게 동작하고 싶은지 확인해야 하기 때문에 스레드가 더 이상 실행되지 않도록 코드 내에서 스레드를 join()해야 합니다.
join()에 필요한 추가 시간 때문에 "나는 내 코드가 응답을 지연시키지 않기를 바란다"고 말할 수 있습니다.이것은 일부 시나리오에서는 완벽하게 유효할 수 있지만, 이제 당신의 코드가 "python과 OS가 정리하기 위해 이리저리 돌아다닌다"는 것을 고려할 필요가 있습니다.퍼포먼스상의 이유로 이것을 실시하는 경우는, 그 동작을 문서화하는 것을 강하게 추천합니다.다른 사용자가 사용할 것으로 예상되는 라이브러리/패키지를 구축하고 있는 경우 특히 그렇습니다.
퍼포먼스상의 이유 이외에는 참가하지 않을 이유가 없습니다.또, 코드의 퍼포먼스가 그다지 좋은 것은 아니라고 생각합니다.
언급URL : https://stackoverflow.com/questions/15085348/what-is-the-use-of-join-in-python-threading
'itsource' 카테고리의 다른 글
ContextLoaderListener는? (0) | 2022.10.25 |
---|---|
운영 체제 정보 가져오기 (0) | 2022.10.25 |
PHP 버전을 PHPStorm으로 설정하려면 어떻게 해야 하나요? (0) | 2022.10.25 |
JavaScript에서 어레이를 비교하는 방법 (0) | 2022.10.25 |
mariabd의 longtext의 JSON이 "데이터베이스 값을 원칙 유형 json으로 변환할 수 없습니다"를 반환합니다. (0) | 2022.10.25 |