Skip to content
Tcl Source Code Ticket Change Details
Login

Ticket Change Details

Overview

Artifact ID: 3dfa47a2afff76c96f0ec86885082f5af2d33171
Ticket: 05d9a601e45db736729ed5b7a260dd675f245bb4
Memory leak with creating and destroying threads from C
User & Date: gustafn2 on 2016-05-13 13:11:26
Changes

  1. icomment:
    You should probably create the thread via Tcl_CreateThread() as shown in your updated program below. For me, this does not appear to leak.
    
    -gustaf
    
    
    ============================================================================
    #include <stdatomic.h>
    #include <pthread.h>
    #include <unistd.h>
    #include <stdio.h>
    #include <time.h>
    #include <tcl.h>
    
    _Atomic unsigned long long threadCount = 0;
    _Atomic unsigned long long interpCount = 0;
    
    static Tcl_ThreadCreateProc threadRunner;
    static Tcl_ThreadCreateType threadRunner(ClientData clientData) {
    	Tcl_Interp *interp;
    	int tclReturnValue;
    
    	threadCount++;
    
    	interp = Tcl_CreateInterp();
    
    	interpCount++;
    
    	tclReturnValue = Tcl_Init(interp);
    	if (tclReturnValue != TCL_OK) {
    		fprintf(stderr, "warning: TclInit() failed.\n");
    	}
    
    	Tcl_DeleteInterp(interp);
    
    	interpCount--;
    
    	Tcl_FinalizeThread();
    
    	threadCount--;
    }
    
    int main(int argc, char **argv) {
    	Tcl_ThreadId threadId;
    	struct timespec sleepTime;
    	int pthreadCreateRet;
    	int idx = 0;
    	int tclMajor, tclMinor, tclPatchLevel;
    
    	Tcl_FindExecutable(argv[0]);
    
    	Tcl_GetVersion(&tclMajor, &tclMinor, &tclPatchLevel, NULL);
    
    	printf("Testing Tcl version %i.%i.%i\n", tclMajor, tclMinor, tclPatchLevel);
    
    	for (idx = 0;; idx++) {
    		if ((idx % 1024) == 0) {
    			idx = 0;
    
    			printf("Thread Count: %llu, Interp Count: %llu\n", threadCount, interpCount);
    		}
    
    		pthreadCreateRet = Tcl_CreateThread(&threadId, threadRunner, NULL, TCL_THREAD_STACK_DEFAULT, TCL_THREAD_NOFLAGS);
    
    		if (pthreadCreateRet != 0) {
    			fprintf(stderr, "error: pthread_create() failed, exiting.\n");
    
    			return(1);
    		}
    
    		sleepTime.tv_sec = 0;
    		sleepTime.tv_nsec = 1000000;
    		nanosleep(&sleepTime, NULL);
    	}
    
    	return(0);
    }
    
  2. login: "gustafn2"
  3. mimetype: "text/plain"
  4. username: "Gustaf Neumann"