티스토리 뷰

파이썬의 threading모듈을 사용하여 for문을 두 개 돌리는 예제를 소개해 보겠다.


import threading #threading 모듈 import

class myThread (threading.Thread): #threading.Thread 상속받음

    def __init__(self, threadID): #초기화 작업
        threading.Thread.__init__(self)
        self.threadID = threadID

    def run(self): #.start()를 했을때 실행될 내용
        print("Starting " + str(self.threadID))
        for i in range(1,101):
            print("{0} {1}".format(self.threadID,i))
        print("Exiting " + str(self.threadID))

thread1 = myThread(1) #thread1생성
thread2 = myThread(2) #thread2생성

thread1.start() #thread1실행
thread2.start() #thread2실행


실행결과

다음과같이 for문 2개가 같이 도는것을 알 수 있다.

크롤링과 같은 작업을 할 때 사용하면 매우 유용하므로 알아두면 좋을 것 같다.


Starting 1
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
1 11
1 12
1 13
1 14
1 15
1 16
1 17
1 18
Starting 2
2 1
2 2
2 3
2 4
2 5
2 6
2 7
2 8
2 9
2 10
2 11
2 12
2 13
1 19
1 20
1 21
1 22
1 23
1 24
1 25
1 26
1 27
1 28
1 29
1 30
1 31
1 32
1 33
2 14
2 15
2 16
2 17
2 18
2 19
2 20
2 21
2 22
2 23
2 24
2 25
2 26
2 27
2 28
2 29
2 30
2 31
2 32
2 33
1 34
1 35
1 36
1 37
1 38
1 39
1 40
1 41
1 42
1 43
1 44
2 34
2 35
2 36
2 37
2 38
2 39
2 40
2 41
2 42
2 43
2 44
2 45
2 46
2 47
2 48
2 49
2 50
2 51
2 52
2 53
2 54
2 55
2 56
2 57
2 58
2 59
2 60
2 61
1 45
1 46
1 47
1 48
1 49
1 50
1 51
1 52
1 53
1 54
1 55
1 56
2 62
2 63
2 64
2 65
2 66
2 67
2 68
2 69
2 70
2 71
2 72
2 73
2 74
2 75
1 57
1 58
1 59
1 60
1 61
1 62
1 63
1 64
1 65
1 66
1 67
1 68
1 69
1 70
1 71
1 72
1 73
1 74
1 75
1 76
1 77
1 78
1 79
1 80
1 81
1 82
1 83
2 76
2 77
2 78
2 79
2 80
2 81
2 82
2 83
2 84
2 85
2 86
2 87
2 88
2 89
2 90
2 91
2 92
2 93
2 94
2 95
2 96
2 97
1 84
1 85
1 86
1 87
1 88
1 89
1 90
1 91
1 92
1 93
1 94
1 95
1 96
1 97
1 98
1 99
1 100
Exiting 1
2 98
2 99
2 100
Exiting 2

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함