Race condition in pthread_mutex_timedlock?
Luca Bacci
luca.bacci@outlook.com
Sat Oct 24 10:13:02 GMT 2026
I have now changed the code; it should trigger the error quite reliably now.
I am testing on a low-end AMD-based laptop: Ryzen 5 3450U, 16GB RAM,
Windows 11.
Here are a few details about the environment:
lucab@DESKTOP-LOA8DP2 /cygdrive/d
$ uname -r
3.6.11-1.x86_64
lucab@DESKTOP-LOA8DP2 /cygdrive/d
$ cygcheck -c gcc-g++
Cygwin Package Information
Package Version Status
gcc-g++ 14.4.0-1 OK
lucab@DESKTOP-LOA8DP2 /cygdrive/d
$ echo $NUMBER_OF_PROCESSORS
8
*Compilation command:*
lucab@DESKTOP-LOA8DP2 /cygdrive/d
$ gcc -o test-timed-lock test-timed-lock.c
*Error message:*
lucab@DESKTOP-LOA8DP2 /cygdrive/d
$ ./test-timed-lock
assertion "owned == false" failed: file "test-timed-lock.c", line 42,
function: worker_main
Aborted
Thanks a lot! Don't waste time on it if it you can't reproduce.
Luca
On 10/24/2026 9:19 AM, Mark Geisert wrote:
> Hi Luca,
>
> On 10/23/2026 4:57 AM, Luca Bacci wrote:
>> Yeah, that's a good idea :) See the attached STC -- that sample
>> triggers the error quite frequently here (YMMV!)
> Odd, I'm not seeing any error reporting here, in several environments.
> Which version of Cygwin are you running (e.g., 'uname -r') and which
> gcc (e.g., 'cygcheck -c gcc-g++')? How many CPUs (e.g., 'echo
> $NUMBER_OF_PROCESSORS')? How exactly did you compile your source file?
>
> Are you always getting the same error (which one?) or a variety?
> Thanks,
>
> ..mark
-------------- next part --------------
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#include <errno.h>
#include <assert.h>
#include <pthread.h>
#define NUM_THREADS 5
#define ITERATIONS 100000
#define MILLISECONDS 1
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static _Atomic bool owned;
static void
sleep_milliseconds (int milliseconds)
{
struct timespec ts = {
.tv_sec = (milliseconds / 1000),
.tv_nsec = (milliseconds % 1000) * 1000 * 1000
};
nanosleep (&ts, NULL);
}
static void *
worker_main (void *user_data)
{
for (int i = 0; i < ITERATIONS; i++)
{
struct timespec ts;
int ret;
ret = clock_gettime (CLOCK_REALTIME, &ts);
assert (ret == 0);
ret = pthread_mutex_timedlock (&mutex, &ts);
if (ret == ETIMEDOUT)
continue;
assert (ret == 0);
assert (owned == false);
owned = true;
sleep_milliseconds (1);
assert (owned == true);
owned = false;
ret = pthread_mutex_unlock (&mutex);
assert (ret == 0);
}
}
int
main (void)
{
pthread_t threads[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++)
pthread_create (&threads[i], NULL, worker_main, NULL);
for (int i = 0; i < NUM_THREADS; i++)
pthread_join (threads[i], NULL);
return 0;
}
More information about the Cygwin-developers
mailing list