您可以使用构造函数和析构函数(在 gcc 和 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 );
}
}
Run Code Online (Sandbox Code Playgroud)