LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

Sharing a variable between two threads

Dear Sir,
I need to share a single variable between two threads. For example in First

thread I change the value of Varaible(Lets say "a") and as soon as
the
value is
changed, the second thread should respond to the change in the value of
Variable "a".
How can I do this. Could you please help me out in this?
Thanks
Pritpal
0 Kudos
Message 1 of 2
(2,979 Views)
OK, assuming you have two threads thread A and B, and a global variable between them VAR. There are two possible ways to interpret what you want. Either you want:

1) Thread B to wait (block) until thread A sets the value of VAR. Then thread B does something, sets the value of VAR, while thread A is waiting (blocked). When B sets VAR, it goes back to waiting, while thread A runs and sets VAR.

or

2) You want both threads to continue running and processing, thread A writes a value to VAR, thread B is interrupted and gets an event that VAR has changed, and responds. This is a much more complex scenario.

In the case you want scenario 1, (threads that are blocking waiting for a global variable to be set). This is simple and a very common case in multithreading. CVI provides thread safe variables specifically for this purpose. You would create a thread safe variable using the macros defined in CVI. For example, to create and use a thread safe variable, that is an integer called MyCounter. You would do this:

//Before creating the threads, create the variable
DefineThreadSafeScalarVar (int, MyCounter, 0);

/*In each thread, you would access and set the variable through a pointer. This would cause each thread to wait until the pointer had been released by the other thread.*/
int *valuePtr = GetPointerToMyCounter ();

//Insert thread code here to set the variable (*valuePtr)

ReleasePointerToMyCounter ();

//Before shutting down your program, unit the variable
UninitializeMyCounter ();


If you are looking for scenario 2, this is more complicated since it requires events to cause the interrupts of threads that are doing other things. To do this, I wouldn't use one variable, I would use two of CVI's thread safe queues. The thread safe queue provides a built-in callback mechanism, so you wouldn't have to create custom events. There are several examples for programming with thread safe queues under cvi\samples\utility\Threading.

Best Regards,

Chris Matthews
National Instruments
0 Kudos
Message 2 of 2
(2,979 Views)