Can pthread_mutex_lock still work after pthread mutex_destroy ?

Refer:
https://linux.die.net/man/3/pthread_mutex_init
The pthread_mutex_destroy() function shall destroy the mutex object referenced by mutex; the mutex object becomes, in effect, uninitialized. An implementation may cause pthread_mutex_destroy() to set the object referenced by mutex to an invalid value. A destroyed mutex object can be reinitialized using pthread_mutex_init(); the results of otherwise referencing the object after it has been destroyed are undefined.
What is the undefined behavior ?
Let's us wirte sample codes to verify it.
#include <pthread.h>
#include <iostream>
#include <unistd.h>

using namespace std;

static pthread_mutex_t foo_mutex;

static void *
thread1(void *arg)
{
   while(1) {
       pthread_mutex_lock(&foo_mutex);
       cout << "thread 1 running" << endl;
       sleep(2);
   }
}

static void *
thread2(void *arg)
{
   while(1) {
       pthread_mutex_lock(&foo_mutex);
       cout << "thread 2 running" << endl;
       sleep(2);
   }
}

int main()
{
    pthread_mutex_init(&foo_mutex, NULL);
    pthread_mutex_destroy(&foo_mutex);
    pthread_t p1;
    pthread_t p2;
    pthread_create(&p1, 0, thread1, 0);
    pthread_create(&p2, 0, thread2, 0);

    pthread_join(p1, 0);
    pthread_join(p2, 0);

    return 0;
}
~$ g++ -o pmt pmt.cpp -lpthread
~$ ./pmt
thread 1 runningthread 2 running
thread 2 running
thread 1 running
thread 2 running
thread 1 running
thread 2 running
thread 1 running
......
The result is NOT WORK ANY MORE.

No comments:

Post a Comment

fixed: embedded-redis: Unable to run on macOS Sonoma

Issue you might see below error while trying to run embedded-redis for your testing on your macOS after you upgrade to Sonoma. java.la...