\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#218: Tcl Channel Driver Thread State Actions}
\date{September 09, 2004}
\author{Andreas Kupries, Andreas Kupries, Larry W. Virden, David Gravereaux}
\urlstyle{sf}
\setlength{\parskip}{1ex}
\setlength{\parindent}{0pt}
\def\tipversion$#1${\texttt{\$#1\$}}
\def\tiplangle#1{\ensuremath{<}}
\def\tiprangle#1{\ensuremath{>}}
\def\tipbar#1{\ensuremath{|}}
\def\tipmail#1#2{\(\langle\){\small\expandafter\url{#1@#2}}\(\rangle\)}
\ifx\pdfoutput\undefined
\newcommand{\tipimage}[2]{\typeout{Make sure you download #1.eps}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.eps}}{\includegraphics[width=0.8\textwidth]{#1.eps}}}
\newcommand{\tipxref}[1]{}
\newcommand{\tipxrefend}{}
\else
\newcommand{\tipimage}[2]{\typeout{Make sure you create #1.pdf}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.pdf}}{\includegraphics[width=0.8\textwidth]{#1.pdf}}}
\pdfcatalog{/PageMode /UseOutlines}
\newcommand{\tipxref}[1]{\pdfannotlink attr {/C [0.5 0.5 1.0] /Border [0 0 1]} goto name {#1}}
\newcommand{\tipxrefend}{\pdfendlink}
\fi
\newenvironment{tipabstract}{\begin{abstract}}{\end{abstract}}
\begin{document}\maketitle
\begin{center}\begin{tabularx}{\linewidth}{|r@{: }X|}\hline
\textbf{TIP \#218}&\textbf{Tcl Channel Driver Thread State Actions}\\\hline
Author&

Andreas Kupries \tipmail{andreas_kupries}{users.sf.net}
\par
Andreas Kupries \tipmail{akupries}{shaw.ca}
\par
Larry W. Virden \tipmail{lvirden}{yahoo.com}
\par
David Gravereaux \tipmail{davygrvy}{pobox.com}
\\
Created&Thursday, \(\text{9}^{\text{th}}\) September 2004\\
Type&Project\\
Tcl Version&\(8.5\)\\
State&Final\\
Vote&Done\\
Version&\tipversion$Revision: 1.10 $\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

This document specifies a modification of the public definition of channel drivers for the Tcl I/O system to fix a bug in the transfer of channels between threads affecting all drivers requiring thread-specific initialization. The targets for the change are Tcl 8.4.\textit{x} (note that this is an API change to a release) and Tcl 8.5.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Background and Motivation}

The purpose of this TIP is to address and solve a general problem exposed through the actual usage of the ability to transfer any channel between threads. Note that this ability was introduced into the Tcl core before TIPs were used to manage major changes, therefore it is not possible for us here to refer to a TIP. The relevant entry in the Tcl core ChangeLog is of 02-May-2000.

The specific instance of the general problem is logged as SourceForge tracker item 952332[\url{http://sf.net/support/tracker.php?aid=952332}] (a Feature Request in the IOCPSock project). The Socket Channel Driver in the core maintains state not only per channel, but on Windows also per thread. This thread specific state is initialized during the first usage of the \textbf{socket} command at the script-level, i.e. \textit{Tcl\_SocketObjCmd()} at the C-level. The relevant internal function for this is \textit{TclpHasSockets()}.

This causes problems when transferring a socket channel into a thread which has not performed any socket operation before, as the per-thread state of the driver is \textbf{not} initialized at all in that case, causing a crash when trying to use the transfered channel.

This is a general problem all channel drivers maintaining per-thread state will run into. And on Windows most channel drivers will \textbf{have to} maintain per-thread state. This is imposed by the design of the Tcl Notifier. It manages Event Sources on a per-thread basis, and this implies that the Event Source for channel drivers has to maintain, per-thread, a list of the channels belonging to a thread to make setup and checking for events efficient. A process global list would be possible, but would also not be very fast, as it would require locking for each search through it, and such searches happens per iteration per active eventloop per Tcl thread.

What is needed is some way to initialize the thread-specific state of a channel driver for a specific thread, whenever a channel is created within that thread, independent of the method of creation. This can be solved without API changes, if we would restrict ourselves to the channel drivers in the core. This however would make non-core channel drivers second class. To avoid this an official public API is required.

Note that the currently used fix in both 8.4 and 8.5 is an ad-hoc solution without API changes, making external drivers second class. In 8.4 the ad-hoc solution is even incomplete, not covering the sockets, only files.

This TIP has been written to remedy this deficiency for both 8.4 and 8.5.

\section{Specification}

It is possible to solve the specific problem described in the last chapter, by calling the relevant internal function, either in each low-level socket operation, or during the transfer itself. The first will slow down all socket operations (one additional check for per-thread initialization per operation (read, write, seek, ...)), the second introduces code specific to channel types into the transfer code. Neither solution is considered acceptable; they are mere band-aids.

Instead of using one of the band-aids described above, this TIP proposes to solve the general problem of per-thread channel driver initialization by extending the public structure of channel drivers with one new function pointer.

The purpose of this function is not directly the initialization of per-thread information, but to provide the driver with notifications when a channel of its type is removed from or added to a thread, by whatever means (creation, deletion, transfer, ...). This can be used not only to initialize the per-thread data of the channel driver, but for other thread-specific actions of the driver as well.

As we are modifying a public structure, we have to distinguish between older drivers not supporting the new function and new drivers which do. The 'Tcl\_ChannelType' structure contains a version field just for this purpose. Currently known versions of drivers are version 0 to 3, where version 0 is for drivers whose structure does not contain a version field. The modification proposed in this document now introduces channel driver version 4.

\subsection{Details}

The definition of the new version tag is
\begingroup\small\begin{verbatim}
 #define TCL_CHANNEL_VERSION_4 ((Tcl_ChannelTypeVersion) 0x4)
\end{verbatim}
\endgroup

The signature of the new function is
\begingroup\small\begin{verbatim}
 void Tcl_DriverThreadActionProc (ClientData instanceData, int action);

 /* Codes for 'action' */

 #define TCL_CHANNEL_THREAD_INSERT (0)
 #define TCL_CHANNEL_THREAD_REMOVE (1)
\end{verbatim}
\endgroup

The \textit{Tcl\_DriverThreadActionProc} defined for a channel type \textit{FOO} will be called by the core with thread \textit{BAR} as current thread whenever:
\begin{enumerate}
\item{}
a channel of type \textit{FOO} is created in thread \textit{BAR}.
\item{}
a channel of type \textit{FOO} is transfered into the thread \textit{BAR}.
\item{}
a channel of type \textit{FOO} is closed in thread \textit{BAR}.
\item{}
a channel of type \textit{FOO} is transfered out of the thread \textit{BAR}.
\end{enumerate}

For the first two calls we can assert \textit{action == TCL\_CHAN\_THREAD\_INSERT}, and the last two calls can assert \textit{action == TCL\_CHAN\_THREAD\_REMOVE}.

Note that multiple calls of \textit{Tcl\_DriverThreadActionProc} per thread are possible and have to be dealt with correctly.

The new definition of structure \textit{Tcl\_ChannelType} is
\begingroup\small\begin{verbatim}
 typedef struct Tcl_ChannelType {
 [... Existing Definition ...]
     /*
      * Only valid in TCL_CHANNEL_VERSION_4 channels or later
      */
     Tcl_DriverThreadActionProc *threadActionProc;
                                       /* Procedure to call to notify
                                        * the driver of thread specific
                                        * activity for a channel.
                                        * May be NULL. */
 } Tcl_ChannelType;
\end{verbatim}
\endgroup

A new public accessor API is provided as well, returning a pointer to the new function (or NULL if it does not exist).
\begingroup\small\begin{verbatim}
 Tcl_DriverThreadActionProc *
 Tcl_ChannelThreadActionProc(Tcl_ChannelType* typePtr);
\end{verbatim}
\endgroup

\section{Discarded Solutions}

It was initially proposed to extend the driver structure with a function having only a very narrow purpose- the initialization of the thread specific data of the driver.

This was dropped because the solution actually proposed is more general and thus should be more stable in the long term. In other words, we believe that the adoption of the general solution reduces the risk of having to extend the Channel driver API again in the future, compared to the risk of this should we adopt the narrow solution.

Another approach uses the same model as specified here, i.e. general cut and splice functionality, but uses two driver functions to implement this. The problem with this approach is that an implementor of a driver might get confused and realize only one of the two functions, i.e. only part of the required functionality.

\section{Reference Implementation}

A reference implementation is provided at SourceForge [\url{http://sourceforge.net/support/tracker.php?aid=875701}].

\section{Comments}

David Gravereaux has recently tested this with his IOCPSOCK extension (11/26) and found no problems. If it hastens the acceptance of the TIP, David does not need the one export in the patch (\textit{Tcl\_DriverThreadActionProc}) to be exported for his extension to work. Others that do channel chaining (windows expect, for example), will most likely need it.

\section{Copyright}

This document has been placed in the public domain.

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\end{document}
