Reputation: 490
I build a share library that used for LD_PRELOAD
, that library is called by multy-threads in parallel.
I in the first time that read
function call to call for _init
function . I don't want to use __attribute__(constructor)
because that library load lot of time.
#include <stdio.h>
#include <string.h>
#include <pthread.h>
pthread_mutex_t lock;
static int is_init = 0;
pthread_mutex_t lock;
static void __init()
{
is_init = 1;
pthread_mutex_lock(&lock);
////////////////////////////////////////////
if(is_init == 0)
return;
print("init.....\n");
////////////////////////////////////////////
pthread_mutex_unlock(&lock);
}
ssize_t read(int fd, void *data, size_t size) {
if(is_init == 0)
__init();
strcpy(data, "I love cats");
return 12;
}
But how can I init the lock with pthread_mutex_init
that will called only 1 time ?
Upvotes: 0
Views: 634
Reputation: 5830
Either
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
or in the __init
function
pthread_mutex_init(...);
As kaylum said earlier: "the constructor is only called once per process."
Upvotes: 2