LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

thread locks and TSVs

Solved!
Go to solution

Dear threading experts,

 

is there any side effect if I use the macros 'GetPointerTo' and 'ReleasePointerTo' inside a thread lock, that is in code located in between CmtGetLock and CmtReleaseLock?

Phrased differently, what kind of sequence is preferred if I need to modify a TSV within a piece of code that should be accessed only from one thread at a time:

1) 

CmtGetLock

...

CmtReleaseLock

GetPointerTo

...

ReleasePointerTo

CmtGetLock

...

CmtReleaseLock

 

OR 

2)

CmtGetLock

...

GetPointerTo

...

ReleasePointerTo

... 

CmtReleaseLock

  

Thank you!

 

Wolfgang

0 Kudos
Message 1 of 3
(3,501 Views)
Solution
Accepted by topic author Wolfgang

Hi Wolfgang.

 

GetPointerTo.. will block until the thread holding the pointer releases it, so the CmtGetLock() and CmtReleaseLock() calls are unnecessary, unless they are protecting some other variable(s), in which case sequence 2) is the way to go.

 

Remember that if you are using multiple thread safe variables or multiple thread locks, and you need to use more than one at any time, each thread must get and release the pointers / locks in the same order. This avoids the possibility of deadlock. Also, each thread must release the resource as quickly as possible.

 

Example (using thread locks):

 

if(!CmtGetLock(lock1))

  {

  if(!CmtGetLock(lock2))  // Get lock2 only when holding lock1

    {

    ...

    CmtReleaseLock(lock2);  // Always release lock2 before lock1 

    }

  CmtReleaseLock(lock1); 

  }

 

Regards,

Colin.

 

0 Kudos
Message 2 of 3
(3,485 Views)

Thanks, Colin, for pointing out version (2). Indeed I have some code with local variables that should be accessed only from one thread at a time, hence I need the CmtGetLock.

 

Wolfgang

0 Kudos
Message 3 of 3
(3,474 Views)