Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static pthread spinlock initialization exists?

Is there a static initializer for pthread spin lock? I looked at pthread.h, and it doesn't seem like there is one.

I am looking for something similar to PTHREAD_MUTEX_INITIALIZER.

like image 535
Hei Avatar asked Mar 23 '23 03:03

Hei


1 Answers

You can use constructor and destructor (available in gcc and clang)

#include <pthread.h>
#include <stdlib.h>

static pthread_spinlock_t lock;

__attribute__((constructor))
void lock_constructor () {
    if ( pthread_spin_init ( &lock, 0 ) != 0 ) {
        exit ( 1 );
    }
}

int main () {
    if (
        pthread_spin_lock   ( &lock ) != 0 ||
        pthread_spin_unlock ( &lock ) != 0
    ) {
        return 2;
    }
    return 0;
}

__attribute__((destructor))
void lock_destructor () {
    if ( pthread_spin_destroy ( &lock ) != 0 ) {
        exit ( 3 );
    }
}
like image 162
puchu Avatar answered Apr 01 '23 02:04

puchu