05-07-2009 10:21 AM
Dear all,
attempting to convert my single-threaded application to a multithreaded one I have encountered a new obstacle:
I'd like to have one global data structure. This structure needs to be dynamically allocated and reallocated as the number of threads (and thus structure size) depends on the program run / user.
Both the primary thread as well as secondary threads should be able to access this structure, so I need to use a thread safe variable, somehow. All the NI samples I have browsed so far either use a single variable using the DefineThreadSafeScalarVar macro, or a fixed size array using the DefineThreadSafeArrayVar macro...
I have not found an example for this kind of a dynamic array, unfortunately... Would some kind soul be willing to teach me how to accomplish this?
Thanks,
Wolfgang
Solved! Go to Solution.
05-08-2009 09:35 AM
In your case, you should use a scalar TSV that holds the pointer being allocated/reallocated. See the following example of a TSV that mimics a dynamic integer array. In some cases, a better solution would be to have a scalar TSV that holds a list, say, the toolbox ListType.
#include <toolbox.h>
DefineThreadSafeVar(int *, DynMem);
void main(void)
{
int **pDynMem, i;
// Initialize TSV
InitializeDynMem();
// Set TSV 'array' to hold 10 integers
SetDynMem(malloc(10 * sizeof(int)));
// Set and get 'elements' of TSV
pDynMem = GetPointerToDynMem();
for (i = 0; i < 10; ++i)
{
(*pDynMem)[i] = i;
printf("DynMem[%d] = %d\n", (*pDynMem)[i], i);
}
ReleasePointerToDynMem();
// Resize TSV 'array'
pDynMem = GetPointerToDynMem();
*pDynMem = realloc(*pDynMem, 20 * sizeof(int));
for (i = 10; i < 20; ++i)
(*pDynMem)[i] = i;
for (i = 0; i < 20; ++i)
printf("DynMem[%d] = %d\n", (*pDynMem)[i], i);
ReleasePointerToDynMem();
// Free TSV 'array'
pDynMem = GetPointerToDynMem();
free(*pDynMem);
ReleasePointerToDynMem();
// Uninitialize TSV
UninitializeDynMem();
}
05-08-2009 09:36 AM
05-10-2009 09:02 AM
Thank you, Mohan! I consider your example very useful, so let me suggest to add something similar to the official CVI documentation, too.
May be in the form of a '1:1 translation table' such as
single-threaded code multi-threaded code
mydynmem = malloc ( elements * sizeof ( type ) ) Setmydynmem ( malloc ( elements * sizeof ( type ) )
etc. There might be other users wanting to transform a single-threaded to a multi-threaded code.
Wolfgang