Tcl Source Code

Artifact [9ef20b7ecb]
Login

Artifact 9ef20b7ecb14f10b87a0c8becb72d54a7577ffe2:

Attachment "tcl8.5_all_003.diff" to ticket [875701ffff] added by andreas_kupries 2005-01-27 06:43:32.
Index: doc/CrtChannel.3
===================================================================
RCS file: /cvsroot/tcl/tcl/doc/CrtChannel.3,v
retrieving revision 1.24
diff -w -u -r1.24 CrtChannel.3
--- doc/CrtChannel.3	12 Nov 2004 09:01:25 -0000	1.24
+++ doc/CrtChannel.3	26 Jan 2005 23:36:50 -0000
@@ -7,11 +7,11 @@
 '\"
 '\" RCS: @(#) $Id: CrtChannel.3,v 1.24 2004/11/12 09:01:25 das Exp $
 .so man.macros
-.TH Tcl_CreateChannel 3 8.3 Tcl "Tcl Library Procedures"
+.TH Tcl_CreateChannel 3 8.4 Tcl "Tcl Library Procedures"
 .BS
 '\" Note:  do not modify the .SH NAME line immediately below!
 .SH NAME
-Tcl_CreateChannel, Tcl_GetChannelInstanceData, Tcl_GetChannelType, Tcl_GetChannelName, Tcl_GetChannelHandle, Tcl_GetChannelMode, Tcl_GetChannelBufferSize, Tcl_SetChannelBufferSize, Tcl_NotifyChannel, Tcl_BadChannelOption, Tcl_ChannelName, Tcl_ChannelVersion, Tcl_ChannelBlockModeProc, Tcl_ChannelCloseProc, Tcl_ChannelClose2Proc, Tcl_ChannelInputProc, Tcl_ChannelOutputProc, Tcl_ChannelSeekProc, Tcl_ChannelWideSeekProc, Tcl_ChannelSetOptionProc, Tcl_ChannelGetOptionProc, Tcl_ChannelWatchProc, Tcl_ChannelGetHandleProc, Tcl_ChannelFlushProc, Tcl_ChannelHandlerProc, Tcl_IsChannelShared, Tcl_IsChannelRegistered, Tcl_CutChannel, Tcl_SpliceChannel, Tcl_IsChannelExisting, Tcl_ClearChannelHandlers, Tcl_GetChannelThread, Tcl_ChannelBuffered \- procedures for creating and manipulating channels
+Tcl_CreateChannel, Tcl_GetChannelInstanceData, Tcl_GetChannelType, Tcl_GetChannelName, Tcl_GetChannelHandle, Tcl_GetChannelMode, Tcl_GetChannelBufferSize, Tcl_SetChannelBufferSize, Tcl_NotifyChannel, Tcl_BadChannelOption, Tcl_ChannelName, Tcl_ChannelVersion, Tcl_ChannelBlockModeProc, Tcl_ChannelCloseProc, Tcl_ChannelClose2Proc, Tcl_ChannelInputProc, Tcl_ChannelOutputProc, Tcl_ChannelSeekProc, Tcl_ChannelWideSeekProc, Tcl_ChannelSetOptionProc, Tcl_ChannelGetOptionProc, Tcl_ChannelWatchProc, Tcl_ChannelGetHandleProc, Tcl_ChannelFlushProc, Tcl_ChannelHandlerProc, Tcl_ChannelThreadActionProc, Tcl_IsChannelShared, Tcl_IsChannelRegistered, Tcl_CutChannel, Tcl_SpliceChannel, Tcl_IsChannelExisting, Tcl_ClearChannelHandlers, Tcl_GetChannelThread, Tcl_ChannelBuffered \- procedures for creating and manipulating channels
 .SH SYNOPSIS
 .nf
 \fB#include <tcl.h>\fR
@@ -99,6 +99,9 @@
 .VS 8.4
 Tcl_DriverWideSeekProc *
 \fBTcl_ChannelWideSeekProc\fR(\fItypePtr\fR)
+.sp
+Tcl_DriverThreadActionProc *
+\fBTcl_ChannelThreadActionProc\fR(\fItypePtr\fR)
 .VE 8.4
 .sp
 Tcl_DriverSetOptionProc *
@@ -290,10 +293,20 @@
 (thread)global list of all channels (of the current thread).
 Application to a channel still registered in some interpreter
 is not allowed.
+.VS 8.5
+Also notifies the driver if the \fBTcl_ChannelType\fR version is
+\fBTCL_CHANNEL_VERSION_4\fR (or higher), and
+\fBTcl_DriverThreadActionProc\fR is defined for it.
+.VE 8.5
 .PP
 \fBTcl_SpliceChannel\fR adds the specified \fIchannel\fR to the
 (thread)global list of all channels (of the current thread).
 Application to a channel registered in some interpreter is not allowed.
+.VS 8.5
+Also notifies the driver if the \fBTcl_ChannelType\fR version is
+\fBTCL_CHANNEL_VERSION_4\fR (or higher), and
+\fBTcl_DriverThreadActionProc\fR is defined for it.
+.VE 8.5
 .PP
 \fBTcl_ClearChannelHandlers\fR removes all channelhandlers and event
 scripts associated with the specified \fIchannel\fR, thus shutting
@@ -326,6 +339,7 @@
         Tcl_DriverFlushProc *\fIflushProc\fR;
         Tcl_DriverHandlerProc *\fIhandlerProc\fR;
         Tcl_DriverWideSeekProc *\fIwideSeekProc\fR;
+	Tcl_DriverThreadActionProc *\fIthreadActionProc\fR;
 } Tcl_ChannelType;
 .CE
 .PP
@@ -346,6 +360,7 @@
 \fBTcl_ChannelOutputProc\fR, \fBTcl_ChannelSeekProc\fR,
 .VS 8.4
 \fBTcl_ChannelWideSeekProc\fR,
+\fBTcl_ChannelThreadActionProc\fR,
 .VE 8.4
 \fBTcl_ChannelSetOptionProc\fR, \fBTcl_ChannelGetOptionProc\fR,
 \fBTcl_ChannelWatchProc\fR, \fBTcl_ChannelGetHandleProc\fR,
@@ -365,16 +380,25 @@
 a pointer to the string.
 .SS VERSION
 .PP
-The \fIversion\fR field should be set to \fBTCL_CHANNEL_VERSION_2\fR.
-If it is not set to this value \fBTCL_CHANNEL_VERSION_3\fR, then this
-\fBTcl_ChannelType\fR is assumed to have the older structure.  See
+
+The \fIversion\fR field should be set to the version of the structure
+that you require. \fBTCL_CHANNEL_VERSION_2\fR is the minimum recommended.
+.VS 8.4
+\fBTCL_CHANNEL_VERSION_3\fR must be set to specifiy the \fIwideSeekProc\fR member.
+.VE 8.4
+.VS 8.5
+\fBTCL_CHANNEL_VERSION_4\fR must be set to specifiy the
+\fIthreadActionProc\fR member (includes \fIwideSeekProc\fR).
+.VE 8.5
+If it is not set to any of these, then this
+\fBTcl_ChannelType\fR is assumed to have the original structure.  See
 \fBOLD CHANNEL TYPES\fR for more details.  While Tcl will recognize
-and function with either structure, stacked channels must be of at
+and function with either structures, stacked channels must be of at
 least \fBTCL_CHANNEL_VERSION_2\fR to function correctly.
 .PP
 This value can be retrieved with \fBTcl_ChannelVersion\fR, which returns
 .VS 8.4
-one of \fBTCL_CHANNEL_VERSION_3\fR,
+one of \fBTCL_CHANNEL_VERSION_4\fR, \fBTCL_CHANNEL_VERSION_3\fR,
 .VE 8.4
 \fBTCL_CHANNEL_VERSION_2\fR or \fBTCL_CHANNEL_VERSION_1\fR.
 .SS BLOCKMODEPROC
@@ -775,6 +799,36 @@
 .PP
 This value can be retrieved with \fBTcl_ChannelHandlerProc\fR, which returns
 a pointer to the function.
+
+.VS 8.4
+.SS "THREADACTIONPROC"
+.PP
+The \fthreadActionProc\fR field contains the address of the function
+called by the generic layer when a channel is created, closed, or
+going to move to a different thread, i.e. whenever thread-specific
+driver state might have to initialized or updated. It can be NULL.
+The action \fITCL_CHANNEL_THREAD_REMOVE\fR is used to notify the
+driver that it should update or remove any thread-specific data it
+might be maintaining for the channel.
+.PP
+The action \fITCL_CHANNEL_THREAD_INSERT\fR is used to notify the
+driver that it should update or initialize any thread-specific data it
+might be maintaining using the calling thread as the associate. See
+\fBTcl_CutChannel\fR and \fBTcl_SpliceChannel\fR for more detail.
+.PP
+.CS
+typedef void Tcl_DriverThreadActionProc(
+	ClientData \fIinstanceData\fR,
+      int        \fIaction\fR);
+.CE
+.PP
+\fIInstanceData\fR is the same as the value passed to
+\fBTcl_CreateChannel\fR when this channel was created.
+.PP
+These values can be retrieved with \fBTcl_ChannelThreadActionProc\fR,
+which returns a pointer to the function.
+.VE 8.4
+
 .SH TCL_BADCHANNELOPTION
 .PP
 This procedure generates a "bad option" error message in an
Index: generic/tcl.decls
===================================================================
RCS file: /cvsroot/tcl/tcl/generic/tcl.decls,v
retrieving revision 1.107
diff -w -u -r1.107 tcl.decls
--- generic/tcl.decls	21 Jan 2005 22:25:08 -0000	1.107
+++ generic/tcl.decls	26 Jan 2005 23:36:50 -0000
@@ -1984,7 +1984,10 @@
 	    Tcl_ScaleTimeProc** scaleProc,
 	    ClientData* clientData)
 }
-
+# TIP#218 (Driver Thread Actions) davygrvy/akupries ChannelType ver 4
+declare 554 generic {
+    Tcl_DriverThreadActionProc *Tcl_ChannelThreadActionProc(Tcl_ChannelType *chanTypePtr)
+}
 
 ##############################################################################
 
Index: generic/tcl.h
===================================================================
RCS file: /cvsroot/tcl/tcl/generic/tcl.h,v
retrieving revision 1.195
diff -w -u -r1.195 tcl.h
--- generic/tcl.h	21 Jan 2005 22:25:09 -0000	1.195
+++ generic/tcl.h	26 Jan 2005 23:36:50 -0000
@@ -1460,6 +1460,14 @@
 #define TCL_CHANNEL_VERSION_1	((Tcl_ChannelTypeVersion) 0x1)
 #define TCL_CHANNEL_VERSION_2	((Tcl_ChannelTypeVersion) 0x2)
 #define TCL_CHANNEL_VERSION_3	((Tcl_ChannelTypeVersion) 0x3)
+#define TCL_CHANNEL_VERSION_4	((Tcl_ChannelTypeVersion) 0x4)
+
+/*
+ * TIP #218: Channel Actions, Ids for Tcl_DriverThreadActionProc
+ */
+
+#define TCL_CHANNEL_THREAD_INSERT (0)
+#define TCL_CHANNEL_THREAD_REMOVE (1)
 
 /*
  * Typedefs for the various operations in a channel type:
@@ -1495,6 +1503,9 @@
 		    ClientData instanceData, Tcl_WideInt offset,
 		    int mode, int *errorCodePtr));
 
+/* TIP #218, Channel Thread Actions */
+typedef void     (Tcl_DriverThreadActionProc) _ANSI_ARGS_ ((
+		    ClientData instanceData, int action));
 
 /*
  * The following declarations either map ckalloc and ckfree to
@@ -1585,6 +1596,16 @@
 					 * handle 64-bit offsets. May be
 					 * NULL, and must be NULL if
 					 * seekProc is NULL. */
+
+     /*
+      * Only valid in TCL_CHANNEL_VERSION_4 channels or later
+      * TIP #218, Channel Thread Actions
+      */
+     Tcl_DriverThreadActionProc *threadActionProc;
+ 					/* Procedure to call to notify
+ 					 * the driver of thread specific
+ 					 * activity for a channel.
+					 * May be NULL. */
 } Tcl_ChannelType;
 
 /*
Index: generic/tclDecls.h
===================================================================
RCS file: /cvsroot/tcl/tcl/generic/tclDecls.h,v
retrieving revision 1.109
diff -w -u -r1.109 tclDecls.h
--- generic/tclDecls.h	21 Jan 2005 22:25:11 -0000	1.109
+++ generic/tclDecls.h	26 Jan 2005 23:36:50 -0000
@@ -3452,6 +3452,12 @@
 				Tcl_ScaleTimeProc** scaleProc, 
 				ClientData* clientData));
 #endif
+#ifndef Tcl_ChannelThreadActionProc_TCL_DECLARED
+#define Tcl_ChannelThreadActionProc_TCL_DECLARED
+/* 554 */
+EXTERN Tcl_DriverThreadActionProc * Tcl_ChannelThreadActionProc _ANSI_ARGS_((
+				Tcl_ChannelType * chanTypePtr));
+#endif
 
 typedef struct TclStubHooks {
     struct TclPlatStubs *tclPlatStubs;
@@ -4047,6 +4053,7 @@
     int (*tcl_GetEnsembleNamespace) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Command token, Tcl_Namespace ** namespacePtrPtr)); /* 551 */
     void (*tcl_SetTimeProc) _ANSI_ARGS_((Tcl_GetTimeProc* getProc, Tcl_ScaleTimeProc* scaleProc, ClientData clientData)); /* 552 */
     void (*tcl_QueryTimeProc) _ANSI_ARGS_((Tcl_GetTimeProc** getProc, Tcl_ScaleTimeProc** scaleProc, ClientData* clientData)); /* 553 */
+    Tcl_DriverThreadActionProc * (*tcl_ChannelThreadActionProc) _ANSI_ARGS_((Tcl_ChannelType * chanTypePtr)); /* 554 */
 } TclStubs;
 
 #ifdef __cplusplus
@@ -6303,6 +6310,10 @@
 #define Tcl_QueryTimeProc \
 	(tclStubsPtr->tcl_QueryTimeProc) /* 553 */
 #endif
+#ifndef Tcl_ChannelThreadActionProc
+#define Tcl_ChannelThreadActionProc \
+	(tclStubsPtr->tcl_ChannelThreadActionProc) /* 554 */
+#endif
 
 #endif /* defined(USE_TCL_STUBS) && !defined(USE_TCL_STUB_PROCS) */
 
Index: generic/tclIO.c
===================================================================
RCS file: /cvsroot/tcl/tcl/generic/tclIO.c,v
retrieving revision 1.81
diff -w -u -r1.81 tclIO.c
--- generic/tclIO.c	30 Nov 2004 19:34:47 -0000	1.81
+++ generic/tclIO.c	26 Jan 2005 23:36:50 -0000
@@ -1205,18 +1205,19 @@
      * in the list on exit.
      *
      * JH: Could call Tcl_SpliceChannel, but need to avoid NULL check.
+     *
+     * TIP #218.
+     * AK: Just initialize the field to NULL before invoking Tcl_SpliceChannel
+     *     We need Tcl_SpliceChannel, for the threadAction calls.
+     *     There is no real reason to duplicate all of this.
+     * NOTE: All drivers using thread actions now have to perform their TSD
+     *       manipulation only in their thread action proc. Doing it when
+     *       creating their instance structures will collide with the thread
+     *       action activity and lead to damaged lists.
      */
 
-    statePtr->nextCSPtr = tsdPtr->firstCSPtr;
-    tsdPtr->firstCSPtr = statePtr;
-
-    /*
-     * TIP #10. Mark the current thread as the one managing the new
-     *		channel. Note: 'Tcl_GetCurrentThread' returns sensible
-     *		values even for a non-threaded core.
-     */
-
-    statePtr->managingThread = Tcl_GetCurrentThread();
+    statePtr->nextCSPtr = (ChannelState *) NULL;
+    Tcl_SpliceChannel ((Tcl_Channel) chanPtr);
 
     /*
      * Install this channel in the first empty standard channel slot, if
@@ -2382,7 +2383,7 @@
  *	Resets the field 'nextCSPtr' of the specified channel state to NULL.
  *
  * NOTE:
- *	The channel to splice out of the list must not be referenced
+ *	The channel to cut out of the list must not be referenced
  *	in any interpreter. This is something this procedure cannot
  *	check (despite the refcount) because the caller usually wants
  *	fiddle with the channel (like transfering it to a different
@@ -2404,6 +2405,7 @@
 					 * channel out of the list on close. */
     ChannelState *statePtr = ((Channel *) chan)->state;
 					/* state of the channel stack. */
+    Tcl_DriverThreadActionProc *threadActionProc;
 
     /*
      * Remove this channel from of the list of all channels
@@ -2426,8 +2428,12 @@
 
     statePtr->nextCSPtr = (ChannelState *) NULL;
 
-    TclpCutFileChannel(chan);
-    TclpCutSockChannel(chan);
+    /* TIP #218, Channel Thread Actions */
+    threadActionProc = Tcl_ChannelThreadActionProc (Tcl_GetChannelType (chan));
+    if (threadActionProc != NULL) {
+        (*threadActionProc) (Tcl_GetChannelInstanceData(chan),
+			     TCL_CHANNEL_THREAD_REMOVE);
+    }
 }
 
 /*
@@ -2446,7 +2452,7 @@
  *	Nothing.
  *
  * NOTE:
- *	The channel to add to the list must not be referenced in any
+ *	The channel to splice into the list must not be referenced in any
  *	interpreter. This is something this procedure cannot check
  *	(despite the refcount) because the caller usually wants figgle
  *	with the channel (like transfering it to a different thread)
@@ -2464,6 +2470,7 @@
 {
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
     ChannelState *statePtr = ((Channel *) chan)->state;
+    Tcl_DriverThreadActionProc *threadActionProc;
 
     if (statePtr->nextCSPtr != (ChannelState *) NULL) {
 	Tcl_Panic("Tcl_SpliceChannel: trying to add channel used in different list");
@@ -2480,8 +2487,12 @@
 
     statePtr->managingThread = Tcl_GetCurrentThread();
 
-    TclpSpliceFileChannel(chan);
-    TclpSpliceSockChannel(chan);
+    /* TIP #218, Channel Thread Actions */
+    threadActionProc = Tcl_ChannelThreadActionProc (Tcl_GetChannelType (chan));
+    if (threadActionProc != NULL) {
+        (*threadActionProc) (Tcl_GetChannelInstanceData(chan),
+			     TCL_CHANNEL_THREAD_INSERT);
+    }
 }
 
 /*
@@ -8953,6 +8964,8 @@
 	return TCL_CHANNEL_VERSION_2;
     } else if (chanTypePtr->version == TCL_CHANNEL_VERSION_3) {
 	return TCL_CHANNEL_VERSION_3;
+    } else if (chanTypePtr->version == TCL_CHANNEL_VERSION_4) {
+	return TCL_CHANNEL_VERSION_4;
     } else {
 	/*
 	 * In <v2 channel versions, the version field is occupied
@@ -9308,6 +9321,34 @@
     }
 }
 
+/*
+ *----------------------------------------------------------------------
+ *
+ * Tcl_ChannelThreadActionProc --
+ *
+ *      TIP #218, Channel Thread Actions.
+ *	Return the Tcl_DriverThreadActionProc of the channel type.
+ *
+ * Results:
+ *	A pointer to the proc.
+ *
+ * Side effects:
+ *	None.
+ *
+ *----------------------------------------------------------------------
+ */
+
+Tcl_DriverThreadActionProc *
+Tcl_ChannelThreadActionProc(chanTypePtr)
+    Tcl_ChannelType *chanTypePtr;	/* Pointer to channel type. */
+{
+    if (HaveVersion(chanTypePtr, TCL_CHANNEL_VERSION_4)) {
+	return chanTypePtr->threadActionProc;
+    } else {
+	return NULL;
+    }
+}
+
 #if 0
 /*
  * For future debugging work, a simple function to print the flags of
Index: generic/tclInt.h
===================================================================
RCS file: /cvsroot/tcl/tcl/generic/tclInt.h,v
retrieving revision 1.213
diff -w -u -r1.213 tclInt.h
--- generic/tclInt.h	21 Jan 2005 22:25:18 -0000	1.213
+++ generic/tclInt.h	26 Jan 2005 23:36:50 -0000
@@ -1977,10 +1977,6 @@
 MODULE_SCOPE int	TclpObjChdir _ANSI_ARGS_((Tcl_Obj *pathPtr));
 MODULE_SCOPE Tcl_Obj *	TclPathPart _ANSI_ARGS_((Tcl_Interp *interp, 
 			    Tcl_Obj *pathPtr, Tcl_PathPart portion));
-MODULE_SCOPE void	TclpCutFileChannel _ANSI_ARGS_((Tcl_Channel chan));
-MODULE_SCOPE void	TclpCutSockChannel _ANSI_ARGS_((Tcl_Channel chan));
-MODULE_SCOPE void	TclpSpliceFileChannel _ANSI_ARGS_((Tcl_Channel chan));
-MODULE_SCOPE void	TclpSpliceSockChannel _ANSI_ARGS_((Tcl_Channel chan));
 MODULE_SCOPE void	TclpPanic _ANSI_ARGS_(TCL_VARARGS(CONST char *,
 			    format));
 MODULE_SCOPE char *	TclpReadlink _ANSI_ARGS_((CONST char *fileName,
Index: generic/tclStubInit.c
===================================================================
RCS file: /cvsroot/tcl/tcl/generic/tclStubInit.c,v
retrieving revision 1.112
diff -w -u -r1.112 tclStubInit.c
--- generic/tclStubInit.c	21 Jan 2005 22:25:19 -0000	1.112
+++ generic/tclStubInit.c	26 Jan 2005 23:36:51 -0000
@@ -970,6 +970,7 @@
     Tcl_GetEnsembleNamespace, /* 551 */
     Tcl_SetTimeProc, /* 552 */
     Tcl_QueryTimeProc, /* 553 */
+    Tcl_ChannelThreadActionProc, /* 554 */
 };
 
 /* !END!: Do not edit above this line. */
Index: tests/io.test
===================================================================
RCS file: /cvsroot/tcl/tcl/tests/io.test,v
retrieving revision 1.65
diff -w -u -r1.65 io.test
--- tests/io.test	18 Nov 2004 19:22:12 -0000	1.65
+++ tests/io.test	26 Jan 2005 23:36:52 -0000
@@ -1704,6 +1704,12 @@
     set f [open "|[list [interpreter] $path(script) [array get path]]" r]
     set c [gets $f]
     close $f
+    # Added delay to give Windows time to stop the spawned process and clean
+    # up its grip on the file test1. Added delete as proper test cleanup.
+    # The failing tests were 18.1 and 18.2 as first re-users of file "test1".
+    after 10000
+    file delete $path(script)
+    file delete $path(test1)
     set c
 } hello
 
Index: unix/tclUnixChan.c
===================================================================
RCS file: /cvsroot/tcl/tcl/unix/tclUnixChan.c,v
retrieving revision 1.53
diff -w -u -r1.53 tclUnixChan.c
--- unix/tclUnixChan.c	17 Nov 2004 02:51:32 -0000	1.53
+++ unix/tclUnixChan.c	26 Jan 2005 23:36:52 -0000
@@ -232,6 +232,10 @@
 			    int toWrite, int *errorCode));
 static int		FileSeekProc _ANSI_ARGS_((ClientData instanceData,
 			    long offset, int mode, int *errorCode));
+#ifdef DEPRECATED
+static void             FileThreadActionProc _ANSI_ARGS_ ((
+			   ClientData instanceData, int action));
+#endif
 static Tcl_WideInt	FileWideSeekProc _ANSI_ARGS_((ClientData instanceData,
 			    Tcl_WideInt offset, int mode, int *errorCode));
 static void		FileWatchProc _ANSI_ARGS_((ClientData instanceData,
@@ -291,7 +295,7 @@
 
 static Tcl_ChannelType fileChannelType = {
     "file",			/* Type name. */
-    TCL_CHANNEL_VERSION_3,	/* v3 channel */
+    TCL_CHANNEL_VERSION_4,	/* v4 channel */
     FileCloseProc,		/* Close proc. */
     FileInputProc,		/* Input proc. */
     FileOutputProc,		/* Output proc. */
@@ -305,6 +309,11 @@
     NULL,			/* flush proc. */
     NULL,			/* handler proc. */
     FileWideSeekProc,		/* wide seek proc. */
+#ifdef DEPRECATED
+    FileThreadActionProc,       /* thread actions */
+#else
+    NULL,
+#endif
 };
 
 #ifdef SUPPORTS_TTY
@@ -315,7 +324,7 @@
 
 static Tcl_ChannelType ttyChannelType = {
     "tty",			/* Type name. */
-    TCL_CHANNEL_VERSION_2,	/* v2 channel */
+    TCL_CHANNEL_VERSION_4,	/* v4 channel */
     TtyCloseProc,		/* Close proc. */
     FileInputProc,		/* Input proc. */
 #if BAD_TIP35_FLUSH
@@ -332,6 +341,8 @@
     FileBlockModeProc,		/* Set blocking or non-blocking mode.*/
     NULL,			/* flush proc. */
     NULL,			/* handler proc. */
+    NULL,			/* wide seek proc. */
+    NULL,			/* thread action proc. */
 };
 #endif	/* SUPPORTS_TTY */
 
@@ -342,7 +353,7 @@
 
 static Tcl_ChannelType tcpChannelType = {
     "tcp",			/* Type name. */
-    TCL_CHANNEL_VERSION_2,	/* v2 channel */
+    TCL_CHANNEL_VERSION_4,	/* v4 channel */
     TcpCloseProc,		/* Close proc. */
     TcpInputProc,		/* Input proc. */
     TcpOutputProc,		/* Output proc. */
@@ -355,6 +366,8 @@
     TcpBlockModeProc,		/* Set blocking or non-blocking mode.*/
     NULL,			/* flush proc. */
     NULL,			/* handler proc. */
+    NULL,			/* wide seek proc. */
+    NULL,			/* thread action proc. */
 };
 
 
@@ -1821,6 +1834,15 @@
 	fsPtr = (FileState *) ckalloc((unsigned) sizeof(FileState));
     }
 
+#ifdef DEPRECATED
+    if (channelTypePtr == &fileChannelType) {
+        /* TIP #218. Removed the code inserting the new structure
+	 * into the global list. This is now handled in the thread
+	 * action callbacks, and only there.
+	 */
+        fsPtr->nextPtr = NULL;
+    }
+#endif /* DEPRECATED */
     fsPtr->validMask = channelPermissions | TCL_EXCEPTION;
     fsPtr->fd = fd;
 
@@ -3239,13 +3261,13 @@
     return result;
 }
 
+#ifdef DEPRECATED
 /*
  *----------------------------------------------------------------------
  *
- * TclpCutFileChannel --
+ * FileThreadActionProc --
  *
- *	Remove any thread local refs to this channel. See
- *	Tcl_CutChannel for more info.
+ *	Insert or remove any thread local refs to this channel.
  *
  * Results:
  *	None.
@@ -3256,35 +3278,39 @@
  *----------------------------------------------------------------------
  */
 
-void
-TclpCutFileChannel(chan)
-    Tcl_Channel chan;			/* The channel being removed. Must
-                                         * not be referenced in any
-                                         * interpreter. */
+static void
+FileThreadActionProc (instanceData, action)
+     ClientData instanceData;
+     int action;
 {
+    ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
+    FileState *fsPtr = (FileState *) instanceData;
+
+    if (action == TCL_CHANNEL_THREAD_INSERT) {
+        fsPtr->nextPtr       = tsdPtr->firstFilePtr;
+	tsdPtr->firstFilePtr = fsPtr;
+    } else {
+        FileState **nextPtrPtr;
+	int removed = 0;
+
+	for (nextPtrPtr = &(tsdPtr->firstFilePtr); (*nextPtrPtr) != NULL;
+	     nextPtrPtr = &((*nextPtrPtr)->nextPtr)) {
+	    if ((*nextPtrPtr) == fsPtr) {
+	        (*nextPtrPtr) = fsPtr->nextPtr;
+		removed = 1;
+		break;
+	    }
 }
 
 /*
- *----------------------------------------------------------------------
- *
- * TclpSpliceFileChannel --
- *
- *	Insert thread local ref for this channel.
- *	Tcl_SpliceChannel for more info.
- *
- * Results:
- *	None.
- *
- * Side effects:
- *	None. This is a no-op under unix.
- *
- *----------------------------------------------------------------------
+	 * This could happen if the channel was created in one
+	 * thread and then moved to another without updating
+	 * the thread local data in each thread.
  */
 
-void
-TclpSpliceFileChannel(chan)
-    Tcl_Channel chan;			/* The channel being removed. Must
-                                         * not be referenced in any
-                                         * interpreter. */
-{
+	if (!removed) {
+	    Tcl_Panic("file info ptr not on thread channel list");
 }
+    }
+}
+#endif
Index: unix/tclUnixPipe.c
===================================================================
RCS file: /cvsroot/tcl/tcl/unix/tclUnixPipe.c,v
retrieving revision 1.26
diff -w -u -r1.26 tclUnixPipe.c
--- unix/tclUnixPipe.c	6 Oct 2004 16:08:57 -0000	1.26
+++ unix/tclUnixPipe.c	26 Jan 2005 23:36:52 -0000
@@ -71,7 +71,7 @@
 
 static Tcl_ChannelType pipeChannelType = {
     "pipe",			/* Type name. */
-    TCL_CHANNEL_VERSION_2,	/* v2 channel */
+    TCL_CHANNEL_VERSION_4,	/* v4 channel */
     PipeCloseProc,		/* Close proc. */
     PipeInputProc,		/* Input proc. */
     PipeOutputProc,		/* Output proc. */
@@ -84,6 +84,8 @@
     PipeBlockModeProc,		/* Set blocking or non-blocking mode.*/
     NULL,			/* flush proc. */
     NULL,			/* handler proc. */
+    NULL,                       /* wide seek proc */
+    NULL,                       /* thread action proc */
 };
 
 /*
Index: unix/tclUnixSock.c
===================================================================
RCS file: /cvsroot/tcl/tcl/unix/tclUnixSock.c,v
retrieving revision 1.9
diff -w -u -r1.9 tclUnixSock.c
--- unix/tclUnixSock.c	6 Apr 2004 22:25:57 -0000	1.9
+++ unix/tclUnixSock.c	26 Jan 2005 23:36:52 -0000
@@ -147,49 +147,3 @@
 {
     return TCL_OK;
 }
-
-/*
- *----------------------------------------------------------------------
- *
- * TclpCutSockChannel --
- *
- *	Remove any thread local refs to this channel. See
- *	Tcl_CutChannel for more info. Dummy definition.
- *
- * Results:
- *	None.
- *
- * Side effects:
- *	None.
- *
- *----------------------------------------------------------------------
- */
-
-void
-TclpCutSockChannel(chan)
-    Tcl_Channel chan;
-{
-}
-
-/*
- *----------------------------------------------------------------------
- *
- * TclpSpliceSockChannel --
- *
- *	Insert thread local ref for this channel.
- *	Tcl_SpliceChannel for more info. Dummy definition.
- *
- * Results:
- *	None.
- *
- * Side effects:
- *	None.
- *
- *----------------------------------------------------------------------
- */
-
-void
-TclpSpliceSockChannel(chan)
-    Tcl_Channel chan;
-{
-}
Index: win/tclWinChan.c
===================================================================
RCS file: /cvsroot/tcl/tcl/win/tclWinChan.c,v
retrieving revision 1.38
diff -w -u -r1.38 tclWinChan.c
--- win/tclWinChan.c	19 Jan 2005 22:07:41 -0000	1.38
+++ win/tclWinChan.c	26 Jan 2005 23:36:52 -0000
@@ -98,6 +98,8 @@
 			    int flags));
 static void		FileWatchProc _ANSI_ARGS_((ClientData instanceData,
 			    int mask));
+static void             FileThreadActionProc _ANSI_ARGS_ ((
+			   ClientData instanceData, int action));
 
 /*
  * This structure describes the channel type structure for file based IO.
@@ -105,7 +107,7 @@
 
 static Tcl_ChannelType fileChannelType = {
     "file",			/* Type name. */
-    TCL_CHANNEL_VERSION_3,	/* v3 channel */
+    TCL_CHANNEL_VERSION_4,	/* v4 channel */
     FileCloseProc,		/* Close proc. */
     FileInputProc,		/* Input proc. */
     FileOutputProc,		/* Output proc. */
@@ -119,6 +121,7 @@
     NULL,			/* flush proc. */
     NULL,			/* handler proc. */
     FileWideSeekProc,		/* Wide seek proc. */
+    FileThreadActionProc,	/* Thread action proc. */
 };
 
 #if defined(HAVE_NO_SEH) && defined(TCL_MEM_DEBUG)
@@ -430,11 +433,11 @@
 	if (infoPtr == fileInfoPtr) {
             /*
              * This channel exists on the thread local list. It should
-             * have been removed by an earlier call to TclpCutFileChannel,
+             * have been removed by an earlier Threadaction call,
              * but do that now since just deallocating fileInfoPtr would
              * leave an deallocated pointer on the thread local list.
              */
-            TclpCutFileChannel(fileInfoPtr->channel);
+	    FileThreadActionProc(fileInfoPtr,TCL_CHANNEL_THREAD_REMOVE);
             break;
         }
     }
@@ -1307,8 +1310,11 @@
     }
 
     infoPtr = (FileInfo *) ckalloc((unsigned) sizeof(FileInfo));
-    infoPtr->nextPtr = tsdPtr->firstFilePtr;
-    tsdPtr->firstFilePtr = infoPtr;
+    /* TIP #218. Removed the code inserting the new structure
+     * into the global list. This is now handled in the thread
+     * action callbacks, and only there.
+     */
+    infoPtr->nextPtr = NULL;
     infoPtr->validMask = permissions;
     infoPtr->watchMask = 0;
     infoPtr->flags = appendMode;
@@ -1373,10 +1379,9 @@
 /*
  *----------------------------------------------------------------------
  *
- * TclpCutFileChannel --
+ * FileThreadActionProc --
  *
- *	Remove any thread local refs to this channel. See
- *	See Tcl_CutChannel for more info.
+ *	Insert or remove any thread local refs to this channel.
  *
  * Results:
  *	None.
@@ -1387,24 +1392,21 @@
  *----------------------------------------------------------------------
  */
 
-void
-TclpCutFileChannel(chan)
-    Tcl_Channel chan;			/* The channel being removed. Must
-					 * not be referenced in any
-					 * interpreter. */
+static void
+FileThreadActionProc (instanceData, action)
+     ClientData instanceData;
+     int action;
 {
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
-    Channel *chanPtr = (Channel *) chan;
-    FileInfo *infoPtr;
+    FileInfo *infoPtr = (FileInfo *) instanceData;
+
+    if (action == TCL_CHANNEL_THREAD_INSERT) {
+        infoPtr->nextPtr = tsdPtr->firstFilePtr;
+	tsdPtr->firstFilePtr = infoPtr;
+    } else {
     FileInfo **nextPtrPtr;
     int removed = 0;
 
-    if (chanPtr->typePtr != &fileChannelType) {
-	return;
-    }
-
-    infoPtr = (FileInfo *) chanPtr->instanceData;
-
     for (nextPtrPtr = &(tsdPtr->firstFilePtr); (*nextPtrPtr) != NULL;
 	    nextPtrPtr = &((*nextPtrPtr)->nextPtr)) {
 	if ((*nextPtrPtr) == infoPtr) {
@@ -1424,40 +1426,4 @@
 	Tcl_Panic("file info ptr not on thread channel list");
     }
 }
-
-/*
- *----------------------------------------------------------------------
- *
- * TclpSpliceFileChannel --
- *
- *	Insert thread local ref for this channel.
- *	See Tcl_SpliceChannel for more info.
- *
- * Results:
- *	None.
- *
- * Side effects:
- *	Changes thread local list of valid channels.
- *
- *----------------------------------------------------------------------
- */
-
-void
-TclpSpliceFileChannel(chan)
-    Tcl_Channel chan;			/* The channel being removed. Must
-					 * not be referenced in any
-					 * interpreter. */
-{
-    ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
-    Channel *chanPtr = (Channel *) chan;
-    FileInfo *infoPtr;
-
-    if (chanPtr->typePtr != &fileChannelType) {
-	return;
-    }
-
-    infoPtr = (FileInfo *) chanPtr->instanceData;
-
-    infoPtr->nextPtr = tsdPtr->firstFilePtr;
-    tsdPtr->firstFilePtr = infoPtr;
 }
Index: win/tclWinConsole.c
===================================================================
RCS file: /cvsroot/tcl/tcl/win/tclWinConsole.c,v
retrieving revision 1.12
diff -w -u -r1.12 tclWinConsole.c
--- win/tclWinConsole.c	10 Sep 2004 01:52:17 -0000	1.12
+++ win/tclWinConsole.c	26 Jan 2005 23:36:52 -0000
@@ -148,7 +148,7 @@
 static void		ConsoleExitHandler(ClientData clientData);
 static int		ConsoleGetHandleProc(ClientData instanceData,
 			    int direction, ClientData *handlePtr);
-static ThreadSpecificData *ConsoleInit(void);
+static void             ConsoleInit(void);
 static int		ConsoleInputProc(ClientData instanceData, char *buf,
 			    int toRead, int *errorCode);
 static int		ConsoleOutputProc(ClientData instanceData,
@@ -160,6 +160,9 @@
 static void		ProcExitHandler(ClientData clientData);
 static int		WaitForRead(ConsoleInfo *infoPtr, int blocking);
 
+static void             ConsoleThreadActionProc _ANSI_ARGS_ ((
+			   ClientData instanceData, int action));
+
 /*
  * This structure describes the channel type structure for command console
  * based IO.
@@ -167,7 +170,7 @@
 
 static Tcl_ChannelType consoleChannelType = {
     "console",			/* Type name. */
-    TCL_CHANNEL_VERSION_2,	/* v2 channel */
+    TCL_CHANNEL_VERSION_4,	/* v4 channel */
     ConsoleCloseProc,		/* Close proc. */
     ConsoleInputProc,		/* Input proc. */
     ConsoleOutputProc,		/* Output proc. */
@@ -180,6 +183,8 @@
     ConsoleBlockModeProc,	/* Set blocking or non-blocking mode.*/
     NULL,			/* flush proc. */
     NULL,			/* handler proc. */
+    NULL,                       /* wide seek proc */
+    ConsoleThreadActionProc,    /* thread action proc */
 };
 
 /*
@@ -198,7 +203,7 @@
  *----------------------------------------------------------------------
  */
 
-static ThreadSpecificData *
+static void
 ConsoleInit()
 {
     ThreadSpecificData *tsdPtr;
@@ -224,7 +229,6 @@
 	Tcl_CreateEventSource(ConsoleSetupProc, ConsoleCheckProc, NULL);
 	Tcl_CreateThreadExitHandler(ConsoleExitHandler, NULL);
     }
-    return tsdPtr;
 }
 
 /*
@@ -1169,7 +1173,10 @@
 	 */
 
 	Tcl_MutexLock(&consoleMutex);
+	if (infoPtr->threadId != NULL) {
+	    /* TIP #218. When in flight ignore the event, no one will receive it anyway */
 	Tcl_ThreadAlert(infoPtr->threadId);
+	}
 	Tcl_MutexUnlock(&consoleMutex);
     }
 
@@ -1255,7 +1262,10 @@
 	 */
 
 	Tcl_MutexLock(&consoleMutex);
+	if (infoPtr->threadId != NULL) {
+	    /* TIP #218. When in flight ignore the event, no one will receive it anyway */
 	Tcl_ThreadAlert(infoPtr->threadId);
+	}
 	Tcl_MutexUnlock(&consoleMutex);
     }
 
@@ -1290,10 +1300,9 @@
 {
     char encoding[4 + TCL_INTEGER_SPACE];
     ConsoleInfo *infoPtr;
-    ThreadSpecificData *tsdPtr;
     DWORD id, modes;
 
-    tsdPtr = ConsoleInit();
+    ConsoleInit();
 
     /*
      * See if a channel with this handle already exists.
@@ -1304,9 +1313,12 @@
 
     infoPtr->validMask = permissions;
     infoPtr->handle = handle;
+    infoPtr->channel = (Tcl_Channel) NULL;
 
     wsprintfA(encoding, "cp%d", GetConsoleCP());
 
+    infoPtr->threadId = Tcl_GetCurrentThread();
+
     /*
      * Use the pointer for the name of the result channel.
      * This keeps the channel names unique, since some may share
@@ -1318,8 +1330,6 @@
     infoPtr->channel = Tcl_CreateChannel(&consoleChannelType, channelName,
             (ClientData) infoPtr, permissions);
 
-    infoPtr->threadId = Tcl_GetCurrentThread();
-
     if (permissions & TCL_READABLE) {
 	/*
 	 * Make sure the console input buffer is ready for only character
@@ -1360,3 +1370,51 @@
 
     return infoPtr->channel;
 }
+
+/*
+ *----------------------------------------------------------------------
+ *
+ * ConsoleThreadActionProc --
+ *
+ *	Insert or remove any thread local refs to this channel.
+ *
+ * Results:
+ *	None.
+ *
+ * Side effects:
+ *	Changes thread local list of valid channels.
+ *
+ *----------------------------------------------------------------------
+ */
+
+static void
+ConsoleThreadActionProc (instanceData, action)
+     ClientData instanceData;
+     int action;
+{
+    ConsoleInfo *infoPtr = (ConsoleInfo *) instanceData;
+
+    /* We do not access firstConsolePtr in the thread structures. This is
+     * not for all serials managed by the thread, but only those we are
+     * watching. Removal of the filevent handlers before transfer thus
+     * takes care of this structure.
+     */
+
+    Tcl_MutexLock(&consoleMutex);
+    if (action == TCL_CHANNEL_THREAD_INSERT) {
+        /* We can't copy the thread information from the channel when
+	 * the channel is created. At this time the channel back
+	 * pointer has not been set yet. However in that case the
+	 * threadId has already been set by TclpCreateCommandChannel
+	 * itself, so the structure is still good.
+	 */
+
+        ConsoleInit ();
+        if (infoPtr->channel != NULL) {
+	    infoPtr->threadId = Tcl_GetChannelThread (infoPtr->channel);
+	}
+    } else {
+	infoPtr->threadId = NULL;
+    }
+    Tcl_MutexUnlock(&consoleMutex);
+}
Index: win/tclWinPipe.c
===================================================================
RCS file: /cvsroot/tcl/tcl/win/tclWinPipe.c,v
retrieving revision 1.53
diff -w -u -r1.53 tclWinPipe.c
--- win/tclWinPipe.c	1 Dec 2004 23:18:55 -0000	1.53
+++ win/tclWinPipe.c	26 Jan 2005 23:36:52 -0000
@@ -205,6 +205,9 @@
 static int		TempFileName(WCHAR name[MAX_PATH]);
 static int		WaitForRead(PipeInfo *infoPtr, int blocking);
 
+static void             PipeThreadActionProc _ANSI_ARGS_ ((
+			   ClientData instanceData, int action));
+
 /*
  * This structure describes the channel type structure for command pipe
  * based IO.
@@ -212,7 +215,7 @@
 
 static Tcl_ChannelType pipeChannelType = {
     "pipe",			/* Type name. */
-    TCL_CHANNEL_VERSION_2,	/* v2 channel */
+    TCL_CHANNEL_VERSION_4,	/* v4 channel */
     TCL_CLOSE2PROC,		/* Close proc. */
     PipeInputProc,		/* Input proc. */
     PipeOutputProc,		/* Output proc. */
@@ -225,6 +228,8 @@
     PipeBlockModeProc,		/* Set blocking or non-blocking mode.*/
     NULL,			/* flush proc. */
     NULL,			/* handler proc. */
+    NULL,                       /* wide seek proc */
+    PipeThreadActionProc,       /* thread action proc */
 };
 
 /*
@@ -1696,6 +1701,7 @@
     infoPtr->writeBuf = 0;
     infoPtr->writeBufLen = 0;
     infoPtr->writeError = 0;
+    infoPtr->channel = (Tcl_Channel) NULL;
 
     /*
      * Use one of the fds associated with the channel as the
@@ -2977,7 +2983,10 @@
 	 */
 
 	Tcl_MutexLock(&pipeMutex);
+	if (infoPtr->threadId != NULL) {
+	    /* TIP #218. When in flight ignore the event, no one will receive it anyway */
 	Tcl_ThreadAlert(infoPtr->threadId);
+	}
 	Tcl_MutexUnlock(&pipeMutex);
     }
 
@@ -3065,10 +3074,60 @@
 	 */
 
 	Tcl_MutexLock(&pipeMutex);
+	if (infoPtr->threadId != NULL) {
+	    /* TIP #218. When in flight ignore the event, no one will receive it anyway */
 	Tcl_ThreadAlert(infoPtr->threadId);
+	}
 	Tcl_MutexUnlock(&pipeMutex);
     }
 
     return 0;
 }
 
+/*
+ *----------------------------------------------------------------------
+ *
+ * PipeThreadActionProc --
+ *
+ *	Insert or remove any thread local refs to this channel.
+ *
+ * Results:
+ *	None.
+ *
+ * Side effects:
+ *	Changes thread local list of valid channels.
+ *
+ *----------------------------------------------------------------------
+ */
+
+static void
+PipeThreadActionProc (instanceData, action)
+     ClientData instanceData;
+     int action;
+{
+    PipeInfo *infoPtr = (PipeInfo *) instanceData;
+
+    /* We do not access firstPipePtr in the thread structures. This is
+     * not for all pipes managed by the thread, but only those we are
+     * watching. Removal of the filevent handlers before transfer thus
+     * takes care of this structure.
+     */
+
+    Tcl_MutexLock(&pipeMutex);
+    if (action == TCL_CHANNEL_THREAD_INSERT) {
+        /* We can't copy the thread information from the channel when
+	 * the channel is created. At this time the channel back
+	 * pointer has not been set yet. However in that case the
+	 * threadId has already been set by TclpCreateCommandChannel
+	 * itself, so the structure is still good.
+	 */
+
+        PipeInit ();
+        if (infoPtr->channel != NULL) {
+	    infoPtr->threadId = Tcl_GetChannelThread (infoPtr->channel);
+	}
+    } else {
+	infoPtr->threadId = NULL;
+    }
+    Tcl_MutexUnlock(&pipeMutex);
+}
Index: win/tclWinSerial.c
===================================================================
RCS file: /cvsroot/tcl/tcl/win/tclWinSerial.c,v
retrieving revision 1.28
diff -w -u -r1.28 tclWinSerial.c
--- win/tclWinSerial.c	19 Aug 2003 19:39:56 -0000	1.28
+++ win/tclWinSerial.c	26 Jan 2005 23:36:52 -0000
@@ -200,6 +200,9 @@
 				    CONST char *value));
 static DWORD WINAPI		SerialWriterThread(LPVOID arg);
 
+static void             SerialThreadActionProc _ANSI_ARGS_ ((
+			   ClientData instanceData, int action));
+
 /*
  * This structure describes the channel type structure for command serial
  * based IO.
@@ -207,7 +210,7 @@
 
 static Tcl_ChannelType serialChannelType = {
     "serial",			/* Type name. */
-    TCL_CHANNEL_VERSION_2,	/* v2 channel */
+    TCL_CHANNEL_VERSION_4,	/* v4 channel */
     SerialCloseProc,		/* Close proc. */
     SerialInputProc,		/* Input proc. */
     SerialOutputProc,		/* Output proc. */
@@ -220,6 +223,8 @@
     SerialBlockProc,		/* Set blocking or non-blocking mode.*/
     NULL,			/* flush proc. */
     NULL,			/* handler proc. */
+    NULL,                       /* wide seek proc */
+    SerialThreadActionProc,     /* thread action proc */
 };
 
 /*
@@ -1384,7 +1389,10 @@
 	 */
 
 	Tcl_MutexLock(&serialMutex);
+	if (infoPtr->threadId != NULL) {
+	    /* TIP #218. When in flight ignore the event, no one will receive it anyway */
 	Tcl_ThreadAlert(infoPtr->threadId);
+	}
 	Tcl_MutexUnlock(&serialMutex);
     }
 
@@ -1458,16 +1466,25 @@
     int permissions;
 {
     SerialInfo *infoPtr;
-    ThreadSpecificData *tsdPtr;
     DWORD id;
 
-    tsdPtr = SerialInit();
+    SerialInit();
 
     infoPtr = (SerialInfo *) ckalloc((unsigned) sizeof(SerialInfo));
     memset(infoPtr, 0, sizeof(SerialInfo));
 
     infoPtr->validMask = permissions;
     infoPtr->handle = handle;
+    infoPtr->channel       = (Tcl_Channel) NULL;
+    infoPtr->readable      = 0; 
+    infoPtr->writable      = 1;
+    infoPtr->toWrite       = infoPtr->writeQueue = 0;
+    infoPtr->blockTime     = SERIAL_DEFAULT_BLOCKTIME;
+    infoPtr->lastEventTime = 0;
+    infoPtr->lastError     = infoPtr->error = 0;
+    infoPtr->threadId      = Tcl_GetCurrentThread();
+    infoPtr->sysBufRead    = 4096;
+    infoPtr->sysBufWrite   = 4096;
 
     /*
      * Use the pointer to keep the channel names unique, in case
@@ -1479,14 +1496,6 @@
     infoPtr->channel = Tcl_CreateChannel(&serialChannelType, channelName,
 	    (ClientData) infoPtr, permissions);
 
-    infoPtr->readable = 0; 
-    infoPtr->writable = 1;
-    infoPtr->toWrite = infoPtr->writeQueue = 0;
-    infoPtr->blockTime = SERIAL_DEFAULT_BLOCKTIME;
-    infoPtr->lastEventTime = 0;
-    infoPtr->lastError = infoPtr->error = 0;
-    infoPtr->threadId = Tcl_GetCurrentThread();
-    infoPtr->sysBufRead = infoPtr->sysBufWrite = 4096;
 
     SetupComm(handle, infoPtr->sysBufRead, infoPtr->sysBufWrite);
     PurgeComm(handle,
@@ -2158,3 +2167,51 @@
 		"mode pollinterval lasterror queue sysbuffer ttystatus xchar");
     }
 }
+
+/*
+ *----------------------------------------------------------------------
+ *
+ * SerialThreadActionProc --
+ *
+ *	Insert or remove any thread local refs to this channel.
+ *
+ * Results:
+ *	None.
+ *
+ * Side effects:
+ *	Changes thread local list of valid channels.
+ *
+ *----------------------------------------------------------------------
+ */
+
+static void
+SerialThreadActionProc (instanceData, action)
+     ClientData instanceData;
+     int action;
+{
+    SerialInfo *infoPtr = (SerialInfo *) instanceData;
+
+    /* We do not access firstSerialPtr in the thread structures. This is
+     * not for all serials managed by the thread, but only those we are
+     * watching. Removal of the filevent handlers before transfer thus
+     * takes care of this structure.
+     */
+
+    Tcl_MutexLock(&serialMutex);
+    if (action == TCL_CHANNEL_THREAD_INSERT) {
+        /* We can't copy the thread information from the channel when
+	 * the channel is created. At this time the channel back
+	 * pointer has not been set yet. However in that case the
+	 * threadId has already been set by TclpCreateCommandChannel
+	 * itself, so the structure is still good.
+	 */
+
+        SerialInit ();
+        if (infoPtr->channel != NULL) {
+	    infoPtr->threadId = Tcl_GetChannelThread (infoPtr->channel);
+	}
+    } else {
+	infoPtr->threadId = NULL;
+    }
+    Tcl_MutexUnlock(&serialMutex);
+}
Index: win/tclWinSock.c
===================================================================
RCS file: /cvsroot/tcl/tcl/win/tclWinSock.c,v
retrieving revision 1.44
diff -w -u -r1.44 tclWinSock.c
--- win/tclWinSock.c	6 Oct 2004 14:39:20 -0000	1.44
+++ win/tclWinSock.c	26 Jan 2005 23:36:52 -0000
@@ -265,6 +265,10 @@
 				int *errorCodePtr));
 static DWORD WINAPI	    SocketThread _ANSI_ARGS_((LPVOID arg));
 
+static void             TcpThreadActionProc _ANSI_ARGS_ ((
+			   ClientData instanceData, int action));
+
+
 /*
  * This structure describes the channel type structure for TCP socket
  * based IO.
@@ -272,7 +276,7 @@
 
 static Tcl_ChannelType tcpChannelType = {
     "tcp",		    /* Type name. */
-    TCL_CHANNEL_VERSION_2,  /* v2 channel */
+    TCL_CHANNEL_VERSION_4,  /* v4 channel */
     TcpCloseProc,	    /* Close proc. */
     TcpInputProc,	    /* Input proc. */
     TcpOutputProc,	    /* Output proc. */
@@ -285,6 +289,8 @@
     TcpBlockProc,	    /* Set socket into (non-)blocking mode. */
     NULL,		    /* flush proc. */
     NULL,		    /* handler proc. */
+    NULL,                   /* wide seek proc */
+    TcpThreadActionProc,    /* thread action proc */
 };
 
 
@@ -970,7 +976,7 @@
     Tcl_Interp *interp;		/* Unused. */
 {
     SocketInfo *infoPtr = (SocketInfo *) instanceData;
-    SocketInfo **nextPtrPtr;
+    /* TIP #218 */
     int errorCode = 0;
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
 
@@ -995,20 +1001,12 @@
         }
     }
 
-    /*
-     * Remove the socket from socketList.
+    /* TIP #218. Removed the code removing the structure
+     * from the global socket list. This is now done by
+     * the thread action callbacks, and only there. This
+     * happens before this code is called. We can free
+     * without fear of damaging the list.
      */
-
-    WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
-    for (nextPtrPtr = &(tsdPtr->socketList); (*nextPtrPtr) != NULL;
-	 nextPtrPtr = &((*nextPtrPtr)->nextPtr)) {
-	if ((*nextPtrPtr) == infoPtr) {
-	    (*nextPtrPtr) = infoPtr->nextPtr;
-	    break;
-	}
-    }
-    
-    SetEvent(tsdPtr->socketListLock);
     ckfree((char *) infoPtr);
     return errorCode;
 }
@@ -1025,7 +1023,7 @@
  *	Returns a newly allocated SocketInfo.
  *
  * Side effects:
- *	Adds the socket to the global socket list.
+ *	None, except for allocation of memory.
  *
  *----------------------------------------------------------------------
  */
@@ -1049,10 +1047,11 @@
     infoPtr->acceptProcData = NULL;
     infoPtr->lastError = 0;
 
-    WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
-    infoPtr->nextPtr = tsdPtr->socketList;
-    tsdPtr->socketList = infoPtr;
-    SetEvent(tsdPtr->socketListLock);
+    /* TIP #218. Removed the code inserting the new structure
+     * into the global list. This is now handled in the thread
+     * action callbacks, and only there.
+     */
+    infoPtr->nextPtr = NULL;
     
     return infoPtr;
 }
@@ -1069,7 +1068,7 @@
  *	Returns a new SocketInfo, or NULL with an error in interp.
  *
  * Side effects:
- *	Adds a new socket to the socketList.
+ *	None, except for allocation of memory.
  *
  *----------------------------------------------------------------------
  */
@@ -2666,15 +2665,12 @@
     return winSock.getservbyname(name, proto);
 }
 
-
-
 /*
  *----------------------------------------------------------------------
  *
- * TclpCutSockChannel --
+ * TcpThreadActionProc --
  *
- *	Remove any thread local refs to this channel. See
- *	Tcl_CutChannel for more info.
+ *	Insert or remove any thread local refs to this channel.
  *
  * Results:
  *	None.
@@ -2685,31 +2681,41 @@
  *----------------------------------------------------------------------
  */
 
-void
-TclpCutSockChannel(chan)
-    Tcl_Channel chan;			/* The channel being removed. Must
-                                         * not be referenced in any
-                                         * interpreter. */
+static void
+TcpThreadActionProc (instanceData, action)
+     ClientData instanceData;
+     int action;
 {
     ThreadSpecificData *tsdPtr;
-    SocketInfo *infoPtr;
-    SocketInfo **nextPtrPtr;
-    int removed = 0;
-
-    if (Tcl_GetChannelType(chan) != &tcpChannelType) {
-        return;
-    }
+    SocketInfo *infoPtr = (SocketInfo *) instanceData;
+    int      notifyCmd;
 
+    if (action == TCL_CHANNEL_THREAD_INSERT) {
     /*
-     * The initializtion of tsdPtr _after_ we have determined that we
-     * are dealing with socket is necessary. Doing it before causes
-     * the module to access th tdsPtr when it is not initialized yet,
-     * causing a lockup.
+	 * Ensure that socket subsystem is initialized in this thread, or
+	 * else sockets will not work.
      */
 
+        Tcl_MutexLock(&socketMutex);
+	InitSockets();
+	Tcl_MutexUnlock(&socketMutex);
+
     tsdPtr  = TCL_TSD_INIT(&dataKey);
-    infoPtr = (SocketInfo *) Tcl_GetChannelInstanceData (chan);
 
+	WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
+	infoPtr->nextPtr = tsdPtr->socketList;
+	tsdPtr->socketList = infoPtr;
+	SetEvent(tsdPtr->socketListLock);
+
+	notifyCmd = SELECT;
+    } else {
+        SocketInfo **nextPtrPtr;
+	int removed = 0;
+
+	tsdPtr  = TCL_TSD_INIT(&dataKey);
+
+	/* TIP #218, Bugfix: All access to socketList has to be protected by the lock */
+	WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
     for (nextPtrPtr = &(tsdPtr->socketList); (*nextPtrPtr) != NULL;
 	 nextPtrPtr = &((*nextPtrPtr)->nextPtr)) {
 	if ((*nextPtrPtr) == infoPtr) {
@@ -2718,6 +2724,7 @@
 	    break;
 	}
     }
+	SetEvent(tsdPtr->socketListLock);
 
     /*
      * This could happen if the channel was created in one thread
@@ -2729,72 +2736,13 @@
         Tcl_Panic("file info ptr not on thread channel list");
     }
 
-    /*
-     * Stop notifications for the socket to occur in this thread.
-     */
-
-    SendMessage(tsdPtr->hwnd, SOCKET_SELECT,
-		(WPARAM) UNSELECT, (LPARAM) infoPtr);
-}
-
-/*
- *----------------------------------------------------------------------
- *
- * TclpSpliceSockChannel --
- *
- *	Insert thread local ref for this channel.
- *	Tcl_SpliceChannel for more info.
- *
- * Results:
- *	None.
- *
- * Side effects:
- *	Changes thread local list of valid channels.
- *
- *----------------------------------------------------------------------
- */
-
-void
-TclpSpliceSockChannel(chan)
-    Tcl_Channel chan;			/* The channel being removed. Must
-                                         * not be referenced in any
-                                         * interpreter. */
-{
-    ThreadSpecificData *tsdPtr;
-    SocketInfo *infoPtr;
-
-    if (Tcl_GetChannelType(chan) != &tcpChannelType) {
-        return;
+	notifyCmd = UNSELECT;
     }
 
     /*
-     * Ensure that socket subsystem is initialized in this thread, or
-     * else sockets will not work.
-     */
-
-    Tcl_MutexLock(&socketMutex);
-    InitSockets();
-    Tcl_MutexUnlock(&socketMutex);
-
-    /*
-     * The initializtion of tsdPtr _after_ we have determined that we
-     * are dealing with socket is necessary. Doing it before causes
-     * the module to access th tdsPtr when it is not initialized yet,
-     * causing a lockup.
-     */
-
-    tsdPtr  = TCL_TSD_INIT(&dataKey);
-    infoPtr = (SocketInfo *) Tcl_GetChannelInstanceData (chan);
-
-    WaitForSingleObject(tsdPtr->socketListLock, INFINITE);
-    infoPtr->nextPtr = tsdPtr->socketList;
-    tsdPtr->socketList = infoPtr;
-    SetEvent(tsdPtr->socketListLock);
-
-    /*
-     * Ensure that notifications for the socket occur in this thread.
+     * Ensure that, or stop, notifications for the socket occur in this thread.
      */
 
     SendMessage(tsdPtr->hwnd, SOCKET_SELECT,
-		(WPARAM) SELECT, (LPARAM) infoPtr);
+		(WPARAM) notifyCmd, (LPARAM) infoPtr);
 }