Follow @Openwall on Twitter for new release announcements and other news
[<prev] [next>] [thread-next>] [day] [month] [year] [list]
Message-ID: <CABsZaPgPF0HffQm5tuQ3f1SQcRvKPnD0DR7J8TEFPaPCZ3=5_A@mail.gmail.com>
Date: Sun, 3 Jul 2022 00:38:05 +0800
From: William Tang <galaxyking0419@...il.com>
To: musl@...ts.openwall.com
Subject: Spurious wake up in musl

Hi,

According to the about page, the spurious wake up should not be possible:

musl was the first Linux libc to have ..., the first to have condvars
where newly-arrived waiters can't steal wake events from previous
waiters

However, when I use the following code to test spurious wake up:
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

#include <pthread.h>

#define COUNT_MAX 1000000

static int64_t counter = 0;
static pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

static void *thread_func(void *arg)
{
    while (true) {
       pthread_mutex_lock(&mutex);

        if (counter <= 0)
            pthread_cond_wait(&cond_var, &mutex);

        if (counter <= 0) {
            printf("[worker %p] Spurious wakeup occurred! Counter is
%lld!\n", pthread_self(), counter);
           exit(0);
       }

        if (--counter == 0)
            printf("[worker %p] No more work need to be done!\n",
pthread_self());

        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    pthread_t thread_1, thread_2;
    pthread_create(&thread_1, NULL, thread_func, NULL);
    pthread_create(&thread_2, NULL, thread_func, NULL);

    printf("[main] Started working threads: %p, %p\n", thread_1, thread_2);

    for (size_t i = 0; i < COUNT_MAX; ++i) {
        pthread_mutex_lock(&mutex);
        ++counter;
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&cond_var);
    }

    printf("Finished counting to %u\n", COUNT_MAX);

    pthread_join(thread_1, NULL);
    pthread_join(thread_2, NULL);

    return 0;
}

And compile with command "musl-gcc -static main.c", it outputs:
[main] Started working threads: 0x7efc7f212f38, 0x7efc7f1eff38
[worker 0x7efc7f212f38] No more work need to be done!
[worker 0x7efc7f1eff38] No more work need to be done!
[worker 0x7efc7f1eff38] No more work need to be done!
[worker 0x7efc7f1eff38] No more work need to be done!
[worker 0x7efc7f212f38] Spurious wakeup occurred! Counter is 0!

William

Powered by blists - more mailing lists

Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.