[New-bugs-announce] [issue10393] "with" statement isn't thread-safe

Abyx report at bugs.python.org
Fri Nov 12 15:04:00 CET 2010

New submission from Abyx <fl.lllj at gmail.com>:

Code to reproduce the bug:

#include <python.h>
#include <windows.h>

DWORD WINAPI thread_fn(void* code)
	PyGILState_STATE state = PyGILState_Ensure();
	PyRun_SimpleString("with sync: print('.')\n");
	return 0;

int main()
	PyRun_SimpleString("import _thread\n");
	PyRun_SimpleString("sync = _thread.allocate_lock()\n");
	PyThreadState* mainstate = PyEval_SaveThread();

	HANDLE hThread1 = CreateThread(0, 0, thread_fn, 0, 0, 0);
	HANDLE hThread2 = CreateThread(0, 0, thread_fn, 0, 0, 0);
	WaitForSingleObject(hThread1, INFINITE);
	WaitForSingleObject(hThread2, INFINITE);


------------ Output ------
Traceback (most recent call last):
  File "<string>", line 2, in <module>
NameError: name '_[1]' is not defined
----------- End of output -----

Probably both threads uses the same "_" global variable. First thread releases GIL in "print" function, then second thread overwrites "_", and then first thread raises the NameError accessing "_" later. Sometimes (not ever) the "sync" kept locked, and program deadlocks on next "sync.acquire()" call from another thread (if any).

components: Interpreter Core
messages: 121035
nosy: Abyx
priority: normal
severity: normal
status: open
title: "with" statement isn't thread-safe
type: crash
versions: Python 3.1

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list