Lock Sharing

NI-VISA

Lock Sharing

The locking mechanism in VISA is session based, not thread based. Therefore, if multiple threads share the same session, they have the same privileges for accessing the resource. VISA locks will not provide mutual exclusion in this scenario. However, some applications might have separate sessions to a resource for these multiple threads, and might require that all the sessions in the application have the same privileges as the session that locked the resource. In other cases, there might be a need to share locks among sessions in different applications. Essentially, sessions that have a lock to a resource may share the lock with certain sessions, and exclude access from other sessions.

This section discusses the mechanism that makes it possible to share locks. VISA defines a lock type—VI_SHARED_LOCK—that gives exclusive access privileges to a session, along with the capability to share these exclusive privileges at the discretion of the original session. When locking sessions with a shared lock, the locking session gains an access key. The session can then share this lock with any other session by passing the access key. VISA allows user applications to specify an access key to be used for lock sharing, or VISA can generate the access key for an application.

If the application chooses to specify the accessKey, other sessions that want access to the resource must choose the same unique accessKey for locking the resource. Otherwise, when VISA generates the accessKey, the session that gained the shared lock should make the accessKey available to other sessions for sharing access to the locked resource. Before the other sessions can access the locked resource, they must acquire the lock using the same access key in the accessKey parameter of the viLock() operation. Invoking viLock() with the same access key will register the new session with the same access privileges as the original session. All sessions that share a resource should synchronize their accesses to maintain a consistent state of the resource. The following code is an example of obtaining a shared lock with a requested name:

status = viLock(instr, VI_SHARED_LOCK, 15000, "MyLockName", accessKey);

This example attempts to acquire a shared lock with "MyLockName" as the requestedKey and a timeout of 15 s. If the call is successful, accessKey will contain "MyLockName". If you want to have VISA generate a key, simply pass VI_NULL in place of "MyLockName" and VISA will return a unique key in accessKey that other sessions can use for locking the resource.