Sets a mutual exclusion memory lock only if it is not currently held by any PE.
#include <shmem.h> int shmem_test_lock(long *lock);
The shmem_test_lock routine sets a mutual exclusive memory lock and returns 0 if no other PE is currently holding it. If the lock is currently held by a PE, this function does not wait for the lock being freed and returns 1 right away.
This mutual exclusive memory lock is used to protect a critical region being updated simultaneously by multiple PEs. It does not protect the critical region being accessed concurrently by multiple threads in the PE. Moreover, this lock is not a recursive lock. If a PE has already held the lock, the following calls to shmem_set_lock or shmem_test_lock on the same PE will behave like the lock being held by other PE
#include <stdlib.h>
#include <stdio.h>
#include <shmem.h>
int main (int argc, char* argv[])
{
int total_tasks = -1;
int my_task = -1;
start_pes(0);
total_tasks = _num_pes();
if (total_tasks <= 0) {
printf("FAILED\n");
exit(1);
} else {
printf("number of pes is %d\n", total_tasks);
}
if (total_tasks < 2 || total_tasks % 2) {
printf("FAILED: The number of pes should be an even number. (at least 2)\n");
exit(1);
}
my_task = _my_pe();
if (my_task < 0){
printf("FAILED\n");
exit(1);
} else {
printf("my pe id is %d\n", my_task);
}
long *lock = (long *) shmalloc(sizeof(long));
printf("remote lock operations using set_lock ...\n");
shmem_set_lock(lock);
printf("pe %d got the lock\n", my_task);
shmem_clear_lock(lock);
printf("pe %d released the lock\n", my_task);
shmem_barrier_all();
printf("remote lock operations using test_lock ...\n");
while (shmem_test_lock(lock)) {
}
printf("pe %d got the lock\n", my_task);
shmem_clear_lock(lock);
printf("pe %d released the lock\n", my_task);
shmem_barrier_all();
printf("PASSED\n");
return 0;
}
Subroutines: shmem_clear_lock, shmem_set_lock