108 lines
2.5 KiB
C

#ifndef SLOW_H_
#define SLOW_H_
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <pthread.h>
#include <time.h>
int printf_slow(const char* format, ...);
int pisi(const char* sporocilo){
pthread_t tid = pthread_self();
printf("pisi() klicana v niti %u\n", (int)tid);
fflush(0);
return printf_slow("%s", sporocilo);
}
static pthread_mutex_t signal_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t signal_cond = PTHREAD_COND_INITIALIZER;
int locked = 0;
int izberi_indeks(int max_indeks){
struct timespec ts;
pthread_mutex_lock(&signal_mutex);
if(locked==0){
locked=1;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 1;
pthread_cond_timedwait(&signal_cond, &signal_mutex, &ts);
locked=0;
}else{
pthread_cond_signal(&signal_cond);
}
pthread_mutex_unlock(&signal_mutex);
int i = random()%max_indeks;
printf("izbran indeks: %d\n", i);
return i;
}
void povecaj(int *tabela, int indeks){
int v = tabela[indeks];
usleep(1000);
pthread_t tid = pthread_self();
printf("povecaj() klicana v niti %u\n", (int)tid);
fflush(0);
tabela[indeks] = v+1;
}
int printf_slow(const char* format, ...){
// variable arguments list
va_list valist;
int ret_val;
va_start(valist, format);
// calculate length of formated string
int len = vsnprintf(NULL, 0, format, valist)+1;
va_end(valist);
// allocate space for formated string
char *str = (char*)malloc(len*sizeof(char));
// print formated string
va_start(valist, format);
ret_val = vsnprintf(str, len, format, valist);
va_end(valist);
// write string one byte at a time
// with small pauses
for(int i=0; str[i]!=0; i+=1){
write(1, &str[i], 1);
usleep(10);
}
// free the allocated space
free(str);
return ret_val;
}
int snprintf_slow(char* str, int n, const char* format, ...){
va_list valist;
char *str_base = (char*)malloc(n*sizeof(char));
memset(str_base, 0, n*sizeof(char));
int ret_val;
// print formated string
va_start(valist, format);
ret_val = vsnprintf(str_base, n, format, valist);
va_end(valist);
// copy string one byte at a time
// with small pauses
for(int i=0; i<n; i+=1){
str[i] = str_base[i];
usleep(10);
}
// free the allocated space
free(str_base);
return ret_val;
}
#endif //SLOW_H_