LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

thread-safe dynamic arrays

Solved!
Go to solution

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

 

0 Kudos
Message 1 of 4
(4,678 Views)
Solution
Accepted by topic author Wolfgang

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();
}
 

Message 2 of 4
(4,648 Views)
Another solution would be to use a thread safe queue. See the thread safe queue examples.
0 Kudos
Message 3 of 4
(4,646 Views)

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

0 Kudos
Message 4 of 4
(4,617 Views)