LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

getting global variable value from a second thread

Hello,
 
Just a simple question about threads:
Accessing global variables from different threads should happen in a safe way (I'm using CmtGetLock and CmtRelease Lock). My question is: should this only be done when the value of the variable is changed, or also when the value is read?
 
Example:
 
Method1:
 
.............
while (!global_quit);
.............
 
method2:
 
.............
int local_quit = 0;
while (!local_quit){
    CmtGetLock (quitLock);
    local_quit = global_quit;
    CmtReleaseLock (quitLock);
}
.............
 
Should I use method2, or is method1 OK?
 
 
 
 
 
0 Kudos
Message 1 of 6
(3,714 Views)
Hi,
 
The reading of the variable should be protected as well.
 
In method 1 you might not go into the while loop, but in method 2 you are always going to do it at least once.
 
int local_quit = 0;
 
CmtGetLock (quitLock);
local_quit = global_quit;
CmtReleaseLock (quitLock);
 
while (!local_quit)
{
 
   do loop stuff ......
 
    CmtGetLock (quitLock);
    local_quit = global_quit;
    CmtReleaseLock (quitLock);
}
 
Or
 
CmtGetLock (quitLock);
while (!global_quit)
{
     CmtReleaseLock (quitLock);
   
     do loop ......
 
   
    CmtGetLock (quitLock);
}    
 
CmtReleaseLock (quitLock);
Message 2 of 6
(3,702 Views)

Thanks a lot,

I'll keep it in mind Smiley Wink

0 Kudos
Message 3 of 6
(3,698 Views)
Rather than using locks to serialize access to globals, it would be simpler to use "Thread Safe Variables". Refer to the multithreading overview PDF document in the cvi bin folder for more details about this.
Message 4 of 6
(3,663 Views)

Hello Mohan,

My problem about using thread safe variables is that I cannot use the function DefineThreadSafeScalarVar in a h-file. So if I declare the variable (let's say: count) in the main c-file with this function: "DefineThreadSafeScalarVar (int, count, 0);", then I will only be able to use the variable 'count' in this c-file and not in the other files of my project. Is that correct?

0 Kudos
Message 5 of 6
(3,652 Views)
There is also a DeclareThreadSafeScalarVar macro to just declare the variable in the relevant header file. And then, one can call DefineThreadSafeScalarVar in ONE source file to actually define the variable. Then by including the header file, the thread safe variable can be referenced in other source files.
Message 6 of 6
(3,642 Views)