From eed4c15eaf11f228e1c57f46283ff14961a80b87 Mon Sep 17 00:00:00 2001 From: Yongting Lin Date: Sat, 17 May 2025 16:42:38 +0800 Subject: [PATCH] pthread_mutex1: Enable contention on a shared pthread_mutex across processes The original "Contended pthread mutex" test case was unfair when comparing threads and processes, because each process created by fork() used its own copy of the pthread_mutex_t, resulting in no actual contention between processes. To make the test fair and meaningful in both multi-threaded and multi-process modes, this patch modifies the test to allocate a pthread_mutex_t in a shared memory region (mmap), and initializes it with PTHREAD_PROCESS_SHARED so that all processes contend on the same mutex. This change ensures that contention happens on the same mutex object regardless of whether the test is run using threads or processes. Signed-off-by: Yongting Lin --- tests/pthread_mutex1.c | 49 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/tests/pthread_mutex1.c b/tests/pthread_mutex1.c index cfad200..85a8d35 100644 --- a/tests/pthread_mutex1.c +++ b/tests/pthread_mutex1.c @@ -1,15 +1,60 @@ #define _GNU_SOURCE #include +#include +#include char *testcase_description = "Contended pthread mutex"; +#ifdef THREADS pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; +pthread_mutex_t pmutex = &mutex; +#else +static pthread_mutex_t *pmutex = NULL; + +/* + * Alloc a shared memory where it is placing a cross-process + * pthread mutex for verifying its scability of multi-process + */ +void testcase_prepare(unsigned long nr_tasks) +{ + int ret; + void *addr; + + addr = mmap(NULL, sizeof(pthread_mutex_t), + PROT_READ | PROT_WRITE, + MAP_SHARED | MAP_ANONYMOUS, -1, 0); + assert(addr != MAP_FAILED); + + pmutex = (pthread_mutex_t *)addr; + + pthread_mutexattr_t attr; + ret = pthread_mutexattr_init(&attr); + assert(ret == 0); + + ret = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); + assert(ret == 0); + + ret = pthread_mutex_init(pmutex, &attr); + assert(ret == 0); + + pthread_mutexattr_destroy(&attr); +} + +void testcase_cleanup(void) +{ + if (pmutex) { + pthread_mutex_destroy(pmutex); + munmap(pmutex, sizeof(pthread_mutex_t)); + } +} + +#endif void testcase(unsigned long long *iterations, unsigned long nr) { while (1) { - pthread_mutex_lock(&mutex); - pthread_mutex_unlock(&mutex); + pthread_mutex_lock(pmutex); + pthread_mutex_unlock(pmutex); (*iterations)++; }