Skip to content

Instantly share code, notes, and snippets.

@Mufanc
Last active September 8, 2021 14:59
Show Gist options
  • Save Mufanc/97306ff37ff0f66fa7e2a74c876d518a to your computer and use it in GitHub Desktop.
Save Mufanc/97306ff37ff0f66fa7e2a74c876d518a to your computer and use it in GitHub Desktop.
[Python 中的原子操作] 怎样修改全局变量是线程安全的? #Python
  • 举例来说,下面的操作是原子的(Lx 是列表, Dx 是字典,x、y 是对象,i、j 是 int 变量):
L.append(x)
L1.extend(L2)
x = L[i]
x = L.pop()
L1[i:j] = L2
L.sort()
x = y
x.field = y
D[x] = y
D1.update(D2)
D.keys()
  • 这些不是原子的:
i = i+1
L.append(L[-1])
L[i] = L[j]
D[x] = D[x] + 1

官方文档

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment