I am creating a multithreaded application and need to store a string in a thread local variable. I have used CmtGetThreadLocalVar to store and retrieve int's and double's with no problem. For some reason, I am unable to retrieve a string using CmtGetThreadLocalVar after storing it with the same function (i.e. CmtGetThreadLocalVar). Below is a sample created by NI, that I modified slightly to demonstrate the problem. Note that inside the "ThreadFunction" callback, there is a call to the "StringCreate" function, which is suppose to store a string to the thread local variable. After calling the "StringCreate" function, I call ProcessSystemEvents, a short delay, and then attempt to retrieve the string using "CmtGetThreadLocalVar". If you run this code, you will see that the variable "sString" that should contain the last assigned string, does not! Any help would be greatly appreciated
#include
#include
#include "toolbox.h"
#include
int CVICALLBACK ThreadFunction (void *functionData);
void CVICALLBACK StringCreate (char *strToCreate);
void CVICALLBACK StringDiscard (void *threadLocalPtr, int event, void *callbackData, unsigned int threadID);
int tlvHandle;
volatile int quit = 0;
volatile int secondStrCreated = 0;
int main (int argc, char *argv[])
{
int functionId;
if (InitCVIRTE (0, argv, 0) == 0)
return -1; /* out of memory */
CmtNewThreadLocalVar (sizeof(char *), NULL, StringDiscard, NULL, &tlvHandle);
CmtScheduleThreadPoolFunction (DEFAULT_THREAD_POOL_HANDLE, ThreadFunction, "Secondary Thread", &functionId);
StringCreate ("Main Thread");
while (!secondStrCreated)
{
ProcessSystemEvents ();
Delay (0.001);
}
CmtDiscardThreadLocalVar (tlvHandle);
quit = 1;
CmtWaitForThreadPoolFunctionCompletion (DEFAULT_THREAD_POOL_HANDLE, functionId, 0);
return 0;
}
int CVICALLBACK ThreadFunction (void *functionData)
{
char sString[MAX_PATHNAME_LEN];
StringCreate ((char *)functionData);
ProcessSystemEvents ();
Delay (1);
CmtGetThreadLocalVar (tlvHandle, sString);
secondStrCreated = 1;
while (!quit)
{
ProcessSystemEvents ();
Delay (0.001);
}
return 0;
}
void CVICALLBACK StringCreate (char *strToCreate)
{
char **tlvStringPtr;
CmtGetThreadLocalVar (tlvHandle, &tlvStringPtr);
*tlvStringPtr = malloc (strlen (strToCreate) + 1);
strcpy (*tlvStringPtr, strToCreate);
}
void CVICALLBACK StringDiscard (void *threadLocalPtr, int event, void *callbackData, unsigned int threadID)
{
char *str = *(char **)threadLocalPtr;
free (str);
}