'Why is the output so messed up even tho i use threading.Lock()? [closed]
import threading
import time
class Zaehler(threading.Thread):
einaus = threading.Lock()
def __init__(self):
super().__init__()
self.count = 1
def run(self):
for a in range(10):
#Critical Section
with Zaehler.einaus:
self.count += a
print(self.count)
#Critical Section
meine_threads = []
thread = Zaehler()
thread2 = Zaehler()
#thread3 = Zaehler()
meine_threads.append(thread)
meine_threads.append(thread2)
#meine_threads.append(thread3)
thread.start()
thread2.start()
#thread3.start()
for t in meine_threads:
t.join()
OUTPUT:
1
2
4
7
11
16
22
29
37
46
1
2
4
7
11
16
22
29
37
46
Process finished with exit code 0
This program has only one goal. To understand Locking() :). The variable count is the shared resource which the threads are outputing after the counted the variable up. But instead of giving ( 1, 2, 3, 4, 5, 6 ....) I get the output (1, 2, 4, 7, 11, 16, 22 )
Solution 1:[1]
This is caused by the line self.count += a. You're not incrementing the value by 1, but by the current index. So the first iteration is count + 1 with count equals to 1, then count + 2 with count equals to 2 (because you changed it in the previous iteration), ... Simply use a self.count += 1.
The second thing is that your count variable is not static, that means that each instance of the object gets its own variables, local to the current object, that's why the second object starts at 1 again. If you want it to be global to all instances, just declare it outside any method (like you did for the lock)
Solution 2:[2]
The lock is working fine, the issue is in the loop. Try a simple code without threads
count = 1
for a in range(10):
x += a
print(count)
this will print the same output, since you increase count by a in every iteration
1
2
4
7
11
16
22
29
37
46
To get the output as 1, 2, 3, 4... you can do something like this for example
count = 0
for a in range(10):
count += 1
print(count)
Solution 3:[3]
I am not sure if I understand your question correctly but it seems that you add a to count instead of 1 each time
self.count += a
# should be self.count += 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ladislus |
| Solution 2 | |
| Solution 3 | jonrsharpe |
