Fixed issue #5122: Synchronize tk load failure check to prevent a
potential deadlock.
diff --git a/Modules/tkappinit.c b/Modules/tkappinit.c
index de04b0d..cfbd20c 100644
--- a/Modules/tkappinit.c
+++ b/Modules/tkappinit.c
@@ -16,11 +16,21 @@
 #include <tcl.h>
 #include <tk.h>
 
+#include "tkinter.h"
+
+#ifdef TKINTER_PROTECT_LOADTK
+/* See Tkapp_TkInit in _tkinter.c for the usage of tk_load_faile */
+static int tk_load_failed;
+#endif
+
 int
 Tcl_AppInit(Tcl_Interp *interp)
 {
 	Tk_Window main_window;
-	const char * _tkinter_skip_tk_init;
+	const char *_tkinter_skip_tk_init;
+#ifdef TKINTER_PROTECT_LOADTK
+	const char *_tkinter_tk_failed;
+#endif
 
 #ifdef TK_AQUA
 #ifndef MAX_PATH_LEN
@@ -74,12 +84,32 @@
 		/* Initialize modules that don't require Tk */
 #endif
 
-	_tkinter_skip_tk_init =	Tcl_GetVar(interp, "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY);
-	if (_tkinter_skip_tk_init != NULL && strcmp(_tkinter_skip_tk_init, "1")	== 0) {
+	_tkinter_skip_tk_init =	Tcl_GetVar(interp,
+			"_tkinter_skip_tk_init", TCL_GLOBAL_ONLY);
+	if (_tkinter_skip_tk_init != NULL &&
+			strcmp(_tkinter_skip_tk_init, "1") == 0) {
 		return TCL_OK;
 	}
-	if (Tk_Init(interp) == TCL_ERROR)
+
+#ifdef TKINTER_PROTECT_LOADTK
+	_tkinter_tk_failed = Tcl_GetVar(interp,
+			"_tkinter_tk_failed", TCL_GLOBAL_ONLY);
+
+	if (tk_load_failed || (
+				_tkinter_tk_failed != NULL &&
+				strcmp(_tkinter_tk_failed, "1") == 0)) {
+		Tcl_SetResult(interp, TKINTER_LOADTK_ERRMSG, TCL_STATIC);
 		return TCL_ERROR;
+	}
+#endif
+
+	if (Tk_Init(interp) == TCL_ERROR) {
+#ifdef TKINTER_PROTECT_LOADTK
+		tk_load_failed = 1;
+		Tcl_SetVar(interp, "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY);
+#endif
+		return TCL_ERROR;
+	}
 
 	main_window = Tk_MainWindow(interp);