Skip to content

Commit

Permalink
lib: posix: pthread_key: use spinlock instead of semaphore
Browse files Browse the repository at this point in the history
None of the operations that `pthread_key_sem` protected were
blocking, so simply make it a spinlock.

Also made the lock static.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
  • Loading branch information
cfriedt committed Nov 19, 2022
1 parent 6f9271c commit 0c8e927
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions lib/posix/pthread_key.c
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@

#include "posix_internal.h"

struct k_sem pthread_key_sem;

K_SEM_DEFINE(pthread_key_sem, 1, 1);
static struct k_spinlock pthread_key_lock;

/**
* @brief Create a key for thread-specific data
Expand Down Expand Up @@ -49,8 +47,9 @@ int pthread_key_delete(pthread_key_t key)
pthread_key_obj *key_obj = (pthread_key_obj *)key;
pthread_key_data *key_data;
sys_snode_t *node_l, *next_node_l;
k_spinlock_key_t key_key;

k_sem_take(&pthread_key_sem, K_FOREVER);
key_key = k_spin_lock(&pthread_key_lock);

/* Delete thread-specific elements associated with the key */
SYS_SLIST_FOR_EACH_NODE_SAFE(&(key_obj->key_data_l),
Expand All @@ -66,7 +65,7 @@ int pthread_key_delete(pthread_key_t key)

k_free((void *)key_obj);

k_sem_give(&pthread_key_sem);
k_spin_unlock(&pthread_key_lock, key_key);

return 0;
}
Expand All @@ -82,14 +81,15 @@ int pthread_setspecific(pthread_key_t key, const void *value)
struct posix_thread *thread = to_posix_thread(pthread_self());
pthread_key_data *key_data;
pthread_thread_data *thread_spec_data;
k_spinlock_key_t key_key;
sys_snode_t *node_l;
int retval = 0;

/* Traverse the list of keys set by the thread, looking for key.
* If the key is already in the list, re-assign its value.
* Else add the key to the thread's list.
*/
k_sem_take(&pthread_key_sem, K_FOREVER);
key_key = k_spin_lock(&pthread_key_lock);

SYS_SLIST_FOR_EACH_NODE(&(thread->key_list), node_l) {

Expand Down Expand Up @@ -128,7 +128,7 @@ int pthread_setspecific(pthread_key_t key, const void *value)
}

out:
k_sem_give(&pthread_key_sem);
k_spin_unlock(&pthread_key_lock, key_key);

return retval;
}
Expand All @@ -145,8 +145,9 @@ void *pthread_getspecific(pthread_key_t key)
pthread_thread_data *thread_spec_data;
void *value = NULL;
sys_snode_t *node_l;
k_spinlock_key_t key_key;

k_sem_take(&pthread_key_sem, K_FOREVER);
key_key = k_spin_lock(&pthread_key_lock);

node_l = sys_slist_peek_head(&(thread->key_list));

Expand All @@ -161,7 +162,7 @@ void *pthread_getspecific(pthread_key_t key)
}
}

k_sem_give(&pthread_key_sem);
k_spin_unlock(&pthread_key_lock, key_key);

return value;
}

0 comments on commit 0c8e927

Please sign in to comment.