#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_once_t once_block = PTHREAD_ONCE_INIT;
pthread_mutex_t mutex;
void once_init_routine(void)
{
int status;
status = pthread_mutex_init(&mutex, NULL);
if (status != 0) {
perror("Init Mutex error!");
}
printf("once_init_routine success!\n");
}
void *thread_routine(void *arg)
{
int status;
status = pthread_once(&once_block, once_init_routine);
if (status != 0) {
perror("pthread_once error!\n");
}
status = pthread_mutex_lock(&mutex);
if (status != 0) {
perror("Lock mutex error!");
}
printf("thread routine has locked the mutex.\n");
status = pthread_mutex_unlock(&mutex);
if (status != 0) {
perror("pthread_mutex_unlock() error!");
}
return 0;
}
int main(int argc, char *argv[])
{
pthread_t thread_id;
int status;
status = pthread_create(&thread_id, NULL, thread_routine, NULL);
if (status != 0) {
perror("pthread_create() error!");
}
status = pthread_once(&once_block, once_init_routine);
if (status != 0) {
perror("pthread_once() error!");
}
status = pthread_mutex_lock(&mutex);
if (status != 0) {
perror("pthread_mutex_lock error!");
}
printf("Main has locked the mutex.\n");
status = pthread_mutex_unlock(&mutex);
if (status != 0) {
perror("pthread_mutex_unlock()!");
}
status = pthread_join(thread_id, NULL);
if (status != 0) {
exit(-1);
}
return 0;
}