0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python マルチスレッド 並列処理 の簡単サンプル

Posted at

import threading 
  
# global variable x 
x = 0
  
def increment(): 
    """ 
    function to increment global variable x 
    """
    global x 
    x += 1
  
def thread_task(lock): 
    """ 
    task for thread 
    calls increment function 100000 times. 
    """
    for _ in range(100000): 
        lock.acquire() # ロック ※1
        increment() 
        lock.release() # ロック解除 ※1
  
def main_task(): 
    global x 
    # setting global variable x as 0 
    x = 0
  
    # creating a lock 
    lock = threading.Lock() 
  
    # creating threads 
    t1 = threading.Thread(target=thread_task, args=(lock,)) 
    t2 = threading.Thread(target=thread_task, args=(lock,)) 
  
    # start threads 
    t1.start() 
    t2.start() 
  
    # t1, t2 を順番処理させる 
    t1.join()  #※2
    t2.join()  #※2
  
if __name__ == "__main__": 
    for i in range(10): 
        main_task() 
        print("Iteration {0}: x = {1}".format(i,x)) 

正しい結果

Iteration 0: x = 200000
Iteration 1: x = 200000
Iteration 2: x = 200000
Iteration 3: x = 200000
Iteration 4: x = 200000
Iteration 5: x = 200000
Iteration 6: x = 200000
Iteration 7: x = 200000
Iteration 8: x = 200000
Iteration 9: x = 200000

ちなみに
※1の部分だけをコメントアウトすると

Iteration 0: x = 184418
Iteration 1: x = 177826
Iteration 2: x = 200000
Iteration 3: x = 150490
Iteration 4: x = 179985
Iteration 5: x = 200000
Iteration 6: x = 176347
Iteration 7: x = 165817
Iteration 8: x = 176203
Iteration 9: x = 132321

※2の部分だけをコメントアウトすると

Iteration 0: x = 23071
Iteration 1: x = 18026
Iteration 2: x = 32923
Iteration 3: x = 7482
Iteration 4: x = 102353
Iteration 5: x = 65894
Iteration 6: x = 65155
Iteration 7: x = 52110
Iteration 8: x = 41988
Iteration 9: x = 52410

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?