10-10-2014 10:51 AM
Hi,
Take a look to the code below...
BOOL BVariableCopied;
void main (int argc, char *argv[])
{
int a = 0;
while (TRUE) {
BVariableCopied = FALSE;
CmtScheduleThreadPoolFunction (DEFAULT_THREAD_POOL_HANDLE, ThreadFunction, &a, NULL);
while (!BVariableCopied ) {
Delay (0,01);
}
a++;
}
int CVICALLBACK ThreadFunction(void *data)
{
int a = *(int*)data;
BVariableCopied = TRUE;
......
return TRUE;
}
There's a mode to keep the code more effient end elegant ? I would not to use the while/delay to wait for the ThreadFunction calling.
Thanks for your precious support
Tavella fabrizio
Micro Systems S.p.A.
10-11-2014 01:00 AM
Take a look to this solution.
There are errors or can it work as expected?
void main (int argc, char *argv[])
{
int a = 0;
int *b;
while (TRUE) {
b = (int*)calloc (1, sizeof (int));
*b = a;
CmtScheduleThreadPoolFunction (DEFAULT_THREAD_POOL_HANDLE, ThreadFunction, b, NULL);
a++;
}
int CVICALLBACK ThreadFunction(void *data)
{
......
free (data);
return TRUE;
}
Thanks again
Tavella Fabrizio
Micro Systems S.p.A.
10-13-2014 01:33 AM
Yes, the previous one was another bad solution...
Take a look to this new solution.
It should work properly.
Have you suggestions?
int a[10];
void main (int argc, char *argv[])
{
int index = 0;
while (index < 10) {
a[index] = arbitrary value;
CmtScheduleThreadPoolFunction (DEFAULT_THREAD_POOL_HANDLE, ThreadFunction, &a[index], NULL);
index++;
}
int CVICALLBACK ThreadFunction(void *data)
{
int a;
a = *((int *)data);
......
return TRUE;
}
Thanks again
Tavella Fabrizio
Micro Systems S.p.A.
10-13-2014 02:09 AM
Unfortunately, even if it formally will work, you cannot pass the value this way.
Working in a multithreading environment, you cannot pass a pointer to a variable that you are not certain it will remain valid until the spawned thread will finish or it won't be manipulated by other treads while the one you are interested into is working. If your aim is to manipulate a global object in a second thread, you should at least protect it with the appropriate Thread Safe Variables functions and macros.
If you want to be sure to wait for the thread to finish before proceding with the execution (as in your example #1) you can use CmtWaitForThreadPoolFunctionCompletion function or the alternatives listed in the corresponding help page.
This white paper can be of help while starting to design a multithreaded application in CVI