rt_benchs/communication_techniques/src/communication/common.c

86 lines
1.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
/* Non standard include */
#include <specific_comm.h>
#include <commtech.h>
struct thread_comm *tcomms;
volatile int cont = 1;
static int init = 0;
static int error = 0;
static pthread_mutex_t init_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t init_cond = PTHREAD_COND_INITIALIZER;
int init_library(void)
{
tcomms = (struct thread_comm *) malloc(nb_prod * sizeof(struct thread_comm));
if (tcomms == NULL)
{
fprintf(stderr, "Failed to allocate %lu bytes needed by the library to work\n", nb_prod * sizeof(struct thread_comm));
return -1;
}
return 0;
}
int end_library(void)
{
free(tcomms);
return 0;
}
int get_thread_number(void)
{
static int i = 0;
static pthread_mutex_t i_lock = PTHREAD_MUTEX_INITIALIZER;
int i_local;
pthread_mutex_lock(&i_lock);
i_local = i;
i++;
pthread_mutex_unlock(&i_lock);
return i_local;
}
int init_producer_thread(void)
{
int thread_num;
thread_num = get_thread_number();
if (init_thread_comm(&tcomms[thread_num]))
{
pthread_mutex_lock(&init_lock);
error = 1;
pthread_cond_signal(&init_cond);
pthread_mutex_unlock(&init_lock);
return -1;
}
if (thread_num == nb_prod - 1)
{
pthread_mutex_lock(&init_lock);
init = 1;
pthread_cond_signal(&init_cond);
pthread_mutex_unlock(&init_lock);
}
return 0;
}
int end_producer_thread(void)
{
return end_thread_comm();
}
int wait_initialization(void)
{
pthread_mutex_lock(&init_lock);
if (!init && !error)
pthread_cond_wait(&init_cond, &init_lock);
pthread_mutex_unlock(&init_lock);
if (error)
return -1;
return 0;
}