파이썬에서 스레드 만들기
스크립트가 있는데 한 함수가 다른 함수와 동시에 실행되기를 원합니다.
내가 본 예제 코드 :
import threading
def MyThread (threading.thread):
# doing something........
def MyThread2 (threading.thread):
# doing something........
MyThread().start()
MyThread2().start()
이 작업을 수행하는 데 문제가 있습니다. 클래스가 아닌 스레드 함수를 사용 하여이 작업을 선호합니다.
이것은 작동하는 스크립트입니다.
from threading import Thread
class myClass():
def help(self):
os.system('./ssh.py')
def nope(self):
a = [1,2,3,4,5,6,67,78]
for i in a:
print i
sleep(1)
if __name__ == "__main__":
Yep = myClass()
thread = Thread(target = Yep.help)
thread2 = Thread(target = Yep.nope)
thread.start()
thread2.start()
thread.join()
print 'Finished'
Thread
이 작업을 수행하기 위해 서브 클래스를 사용할 필요가 없습니다. 아래에 게시하는 간단한 예제를 살펴보고 방법을 확인하십시오.
from threading import Thread
from time import sleep
def threaded_function(arg):
for i in range(arg):
print("running")
sleep(1)
if __name__ == "__main__":
thread = Thread(target = threaded_function, args = (10, ))
thread.start()
thread.join()
print("thread finished...exiting")
여기에서는 스레딩 모듈을 사용하여 일반 함수를 대상으로 호출하는 스레드를 만드는 방법을 보여줍니다. 스레드 생성자에서 필요한 인수를 전달하는 방법을 알 수 있습니다.
코드에 몇 가지 문제가 있습니다.
def MyThread ( threading.thread ):
- 함수로 서브 클래 싱 할 수 없습니다. 수업 만
- 서브 클래스를 사용하려고한다면 threading.thread가 아니라 threading을 원할 것입니다.
If you really want to do this with only functions, you have two options:
With threading:
import threading
def MyThread1():
pass
def MyThread2():
pass
t1 = threading.Thread(target=MyThread1, args=[])
t2 = threading.Thread(target=MyThread2, args=[])
t1.start()
t2.start()
With thread:
import thread
def MyThread1():
pass
def MyThread2():
pass
thread.start_new_thread(MyThread1, ())
thread.start_new_thread(MyThread2, ())
Doc for thread.start_new_thread
I tried to add another join(), and it seems worked. Here is code
from threading import Thread
from time import sleep
def function01(arg,name):
for i in range(arg):
print(name,'i---->',i,'\n')
print (name,"arg---->",arg,'\n')
sleep(1)
def test01():
thread1 = Thread(target = function01, args = (10,'thread1', ))
thread1.start()
thread2 = Thread(target = function01, args = (10,'thread2', ))
thread2.start()
thread1.join()
thread2.join()
print ("thread finished...exiting")
test01()
You can use the target
argument in the Thread
constructor to directly pass in a function that gets called instead of run
.
Did you override the run() method? If you overrided __init__
, did you make sure to call the base threading.Thread.__init__()
?
After starting the two threads, does the main thread continue to do work indefinitely/block/join on the child threads so that main thread execution does not end before the child threads complete their tasks?
And finally, are you getting any unhandled exceptions?
Python 3 has the facility of Launching parallel tasks. This makes our work easier.
It has for thread pooling and Process pooling.
The following gives an insight:
ThreadPoolExecutor Example
import concurrent.futures
import urllib.request
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://some-made-up-domain.com/']
# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
with urllib.request.urlopen(url, timeout=timeout) as conn:
return conn.read()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (url, exc))
else:
print('%r page is %d bytes' % (url, len(data)))
Another Example
import concurrent.futures
import math
PRIMES = [
112272535095293,
112582705942171,
112272535095293,
115280095190773,
115797848077099,
1099726899285419]
def is_prime(n):
if n % 2 == 0:
return False
sqrt_n = int(math.floor(math.sqrt(n)))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True
def main():
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
print('%d is prime: %s' % (number, prime))
if __name__ == '__main__':
main()
참고URL : https://stackoverflow.com/questions/2905965/creating-threads-in-python
'IT' 카테고리의 다른 글
dict.clear ()와 파이썬에서 {} 할당의 차이점 (0) | 2020.06.06 |
---|---|
Common Lisp에서`set`,`setq` 및`setf`의 차이점은 무엇입니까? (0) | 2020.06.06 |
OR 열거 형 항목을 제거하는 방법? (0) | 2020.06.06 |
CURL 명령 행 URL 매개 변수 (0) | 2020.06.06 |
내부 조인으로 PostgreSQL 삭제 (0) | 2020.06.06 |