diff --git a/include/posix/pthread.h b/include/posix/pthread.h index a989f014ce0..350c28e641b 100644 --- a/include/posix/pthread.h +++ b/include/posix/pthread.h @@ -18,14 +18,14 @@ #include enum pthread_state { + /* The thread structure is unallocated and available for reuse. */ + PTHREAD_TERMINATED = 0, /* The thread is running and joinable. */ - PTHREAD_JOINABLE = 0, + PTHREAD_JOINABLE, /* The thread is running and detached. */ PTHREAD_DETACHED, /* A joinable thread exited and its return code is available. */ - PTHREAD_EXITED, - /* The thread structure is unallocated and available for reuse. */ - PTHREAD_TERMINATED + PTHREAD_EXITED }; struct posix_thread { @@ -49,8 +49,8 @@ struct posix_thread { }; /* Pthread detach/joinable */ -#define PTHREAD_CREATE_JOINABLE 0 -#define PTHREAD_CREATE_DETACHED 1 +#define PTHREAD_CREATE_JOINABLE PTHREAD_JOINABLE +#define PTHREAD_CREATE_DETACHED PTHREAD_DETACHED /* Pthread cancellation */ #define _PTHREAD_CANCEL_POS 0 diff --git a/lib/posix/Kconfig b/lib/posix/Kconfig index 62bc3a34413..ef8e6063876 100644 --- a/lib/posix/Kconfig +++ b/lib/posix/Kconfig @@ -30,11 +30,11 @@ config PTHREAD_IPC if PTHREAD_IPC config MAX_PTHREAD_COUNT - int "Maximum pthread count in POSIX application" + int "Maximum simultaneously active pthread count in POSIX application" default 5 range 0 255 help - Mention maximum number of threads in POSIX compliant application. + Maximum number of simultaneously active threads in a POSIX application. config SEM_VALUE_MAX int "Maximum semaphore limit" diff --git a/lib/posix/pthread.c b/lib/posix/pthread.c index f1412d3895d..a2138bbccd3 100644 --- a/lib/posix/pthread.c +++ b/lib/posix/pthread.c @@ -35,7 +35,7 @@ static const pthread_attr_t init_pthread_attrs = { }; static struct posix_thread posix_thread_pool[CONFIG_MAX_PTHREAD_COUNT]; -static u32_t pthread_num; +PTHREAD_MUTEX_DEFINE(pthread_pool_lock); static bool is_posix_prio_valid(u32_t priority, int policy) { @@ -132,6 +132,7 @@ int pthread_create(pthread_t *newthread, const pthread_attr_t *attr, void *(*threadroutine)(void *), void *arg) { s32_t prio; + u32_t pthread_num; pthread_condattr_t cond_attr; struct posix_thread *thread; @@ -145,6 +146,17 @@ int pthread_create(pthread_t *newthread, const pthread_attr_t *attr, return EINVAL; } + pthread_mutex_lock(&pthread_pool_lock); + for (pthread_num = 0; + pthread_num < CONFIG_MAX_PTHREAD_COUNT; pthread_num++) { + thread = &posix_thread_pool[pthread_num]; + if (thread->state == PTHREAD_TERMINATED) { + thread->state = PTHREAD_JOINABLE; + break; + } + } + pthread_mutex_unlock(&pthread_pool_lock); + if (pthread_num >= CONFIG_MAX_PTHREAD_COUNT) { return EAGAIN; } @@ -166,7 +178,6 @@ int pthread_create(pthread_t *newthread, const pthread_attr_t *attr, pthread_cond_init(&thread->state_cond, &cond_attr); sys_slist_init(&thread->key_list); - pthread_num++; *newthread = (pthread_t) k_thread_create(&thread->thread, attr->stack, attr->stacksize,