Skip to content

Instantly share code, notes, and snippets.

@tonyseek
Last active June 14, 2016 06:56
Show Gist options
  • Save tonyseek/68fd7bc43901daff05bdc3720b9ae791 to your computer and use it in GitHub Desktop.
Save tonyseek/68fd7bc43901daff05bdc3720b9ae791 to your computer and use it in GitHub Desktop.
Is there an atomic counter implementation in Python?

Readings

Conclusion

The GIL could not protect a += 1 and a = a + 1 both.

itertools.count() is the only way for atomic increment in Python. It benefits from the C-implemented itertools. Otherwise we need to around the inplace adding operation with threading.Lock().

from dis import dis
def increment1(n):
n += 1
return n
def increment2(n):
n = n + 1
return n
for label, code in [
('n += 1', increment1),
('n = n + 1', increment2),
]:
print('-' * 50)
print '%s' % label
print('')
dis(code)
print('-' * 50)
--------------------------------------------------
n += 1
5 0 LOAD_FAST 0 (n)
3 LOAD_CONST 1 (1)
6 INPLACE_ADD
7 STORE_FAST 0 (n)
6 10 LOAD_FAST 0 (n)
13 RETURN_VALUE
--------------------------------------------------
--------------------------------------------------
n = n + 1
10 0 LOAD_FAST 0 (n)
3 LOAD_CONST 1 (1)
6 BINARY_ADD
7 STORE_FAST 0 (n)
11 10 LOAD_FAST 0 (n)
13 RETURN_VALUE
--------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment