Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8523775
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T07:30:21+00:00 2026-06-11T07:30:21+00:00

I have a Tcl main program and I want to create a C thread

  • 0

I have a Tcl main program and I want to create a C thread from it.
I then would need to share information between the two threads: C thread’s process frequently updated inputs/outputs.
I see two possible solutions to my problem: (1) port Tcl’s Thread Shared Variable to C, but I didn’t see any information about it in the TCL-C API. (2) Create Tcl-C linked Variables and use it as arguments during the C thread creation.
The latter idea doesn’t seem to work. Here is the C code:

#include <tcl.h>

/*
startRoutine
*/
static void startRoutine (ClientData clientData) {
 int *Var;
 Var= (int *) clientData;
 int locA=0;
 int j;
 int k;
 while (1) {    
     if (locA=!*Var) {
         // Modify Tcl-C shared variable
         locA=2 * *Var;
         *Var=locA;
         for (j=0; j<100; j++){}
     } else {
         for (k=0; k<100; k++){}
     }
  }
 }




static int
createThreadC_Cmd(
    ClientData cdata,
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *const objv[])
{

    // Contains the ID of the newly created thread
    Tcl_ThreadId id;    
    // Thread argument
    ClientData limitData;

    // Transfering global var argument to the created thread
    limitData=cdata;

    // Thread creation
    id=0;
    Tcl_CreateThread(&id, startRoutine, limitData, TCL_THREAD_STACK_DEFAULT, TCL_THREAD_NOFLAGS);

    // Wait thread process, before returning to TCL prog
    int i;
    int aa;
    for (i=0 ; i<10000000 ; i++){
        aa=i;
    }

    // Return thread ID to tcl prog to allow mutex use
    Tcl_SetObjResult(interp, Tcl_NewIntObj((int) id));
    return TCL_OK;  
}


int DLLEXPORT

Behavcextension_Init(Tcl_Interp *interp)
{

    if (Tcl_InitStubs(interp, TCL_VERSION, 0) == NULL) {
        return TCL_ERROR;
    }

    // Create global Var
    int *sharedPtr;
    int linkedVar=0;
    sharedPtr=&linkedVar;
    Tcl_LinkVar(interp, "linkedVar", (char *) sharedPtr, TCL_LINK_INT);

    Tcl_CreateObjCommand(interp, 
        "createThreadC", createThreadC_Cmd, sharedPtr, NULL);
    return TCL_OK;

}

Here is the Tcl code:

# linkedVar initial value in Tcl, will be overwritten by C Tcl_LinkVar() function
set linkedVar 98
puts "linkedVar: $linkedVar"

# Thread creation
#------------------
load [file join [pwd] libBehavCextension[info sharedlibextension]]
set threadId [createThreadC]
puts "Created thread $threadId, waiting"
# When Tcl_LinkVar() is called, initiate linkedVar at 2
puts "linkedVar: $linkedVar"

# Function inside thread should modify linkedVar into linkedVar*2
set linkedVar 98
after 5000
puts "linkedVar: $linkedVar"

The terminal output is here:

Main thread ID: tid0xb779b6c0
linkedVar: 98
Created thread -1227252928, waiting
linkedVar: 2
linkedVar: 98

The last result should be 2*98=196. LinkVar creation between Tcl and C is Ok (we get 2 after link creation), but passing LinkVar to the Thread is KO.
Any solution or explanations about why it doesn’t work/what to do to solve it are welcome!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T07:30:23+00:00Added an answer on June 11, 2026 at 7:30 am

    The problem remains the same as in the other question. You’re allocating the storage for the variable on the C side on the C stack in a function that terminates shortly afterwards. It’s Undefined Behavior to refer to that variable (which is linkedVar in Behavcextension_Init) after the termination of the function (Behavcextension_Init). What actually happens is that the actual storage is used for some other function call (doing who knows what) and so the value contained is arbitrary, and changing it can lead to “exciting” behavior.

    You’re looking to have a variable that exists after Behavcextension_Init finishes, so it must not be allocated in the stack of that function. The simplest method is this:

    int DLLEXPORT
    Behavcextension_Init(Tcl_Interp *interp)
    {
        int *sharedPtr;
    
        if (Tcl_InitStubs(interp, TCL_VERSION, 0) == NULL) {
            return TCL_ERROR;
        }
    
        sharedPtr = (int *) Tcl_Alloc(sizeof(int));  // Allocate
        *sharedPtr = 0;                              // Initialize
        Tcl_LinkVar(interp, "linkedVar", (char *) sharedPtr, TCL_LINK_INT);
    
        Tcl_CreateObjCommand(interp, 
            "createThreadC", createThreadC_Cmd, sharedPtr, NULL);
        return TCL_OK;
    }
    

    Caveats

    1. This leaks memory, as there is no matching Tcl_Free for that Tcl_Alloc. For memory allocated once per process, that’s not much of a problem. After all, it’s only a few bytes and the OS will reclaim it at exit.
    2. This is unsafe when reading the variable from a different thread than the one where it was written; there’s simply no guarantee that it will work. It will probably work as it is just an integer, but you’re depending on the hardware to be cooperative. The right thing to do is to allocate a structure containing both the variable and a suitable mutex, and protect the accesses to the variable (whether reads or writes) with the mutex. That in turn requires that you do not use Tcl_LinkVar — it knows nothing about mutex-protected memory — but Tcl_LinkVar is just a wrapper round Tcl_TraceVar that provides a callback that does the coupling between Tcl’s variable (see Tcl_GetVar and Tcl_SetVar) and the C variable; writing your own that knows how to do mutex-protection handling as well is not hard. (If you’re interested, get the source to Tcl_LinkVar and adapt it yourself; it doesn’t use any private API calls.)
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to have two way communication between threads in Tcl and all I
I have two tcl scripts. I want to run the second script when the
Tcl 8.4. I have this namespace tree: namespace eval menu_tree { #-------------------------------------------------------------------------- ## Main
I have a Tcl/Tk app that generates many forms and would like to be
I have a flat Tcl list. Now I want to append a new element
Now here's something interesting. When I have more than one thread in Tcl invoking
I have a question about variables in namespace of TCL. I have two .tcl
I have two question about namespace in Tcl. namespace eval ::dai { set a
I have an array a[]= {34,45,65,55,67} I need C or TCL code to build
I have a shell environment variable PATH_TO_DIR and I want to check in TCL

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.