/* cflags: */
/* linker: mtime.o test.o stat.o -lm -lpthread -lrt */
-#include <pthread.h>
-#include <semaphore.h>
#include <stdio.h>
#include <string.h>
+#include <semaphore.h>
+
+#include <pthread.h>
+#include <unistd.h>
+
#include "mtime.h"
#include "test.h"
-#define NT 2
-
/* global variables */
-dts_t *measure_tab = NULL;
+dts_t *deltas = NULL;
+int nb_measurements = 0;
-char *message = "semaphore";
+char *message = "Semaphore latency";
void (*usage_ext) (FILE *) = NULL;
int (*parse_arg_ext) (char *) = NULL;
-int counter = 0;
-int try = 0;
+pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+volatile int shared_flag = 0;
+ts_t ts1, ts2;
sem_t sem;
+int try = 0;
+int nbtoofast = 0;
-void* trythis (__attribute__((unused)) void *arg)
-{
- sem_wait (&sem);
+#define TIMER 1000
- static ts_t tsi;
- ts_t ts;
- sys_timestamp (&ts);
+void *semaphore_giver_task (__attribute__((unused)) void *arg)
+{
- /* thread 1 took the lock -> timestamp 1 */
- if (counter % 2 == 0) {
- set_timestamp (&tsi, &ts);
+ while (try < nb_measurements) {
+ sem_wait (&sem);
+ usleep (TIMER);
+ shared_flag = 1;
+ sys_timestamp (&ts1);
+ sem_post (&sem);
+ //shared_flag = 0;
+ usleep (TIMER);
}
- /* thread 2 took the lock -> timestamp 2 */
- else {
- measure_tab[try++] = diff_timestamp (&ts, &tsi);
- }
+ pthread_exit (NULL);
+}
- counter += 1;
+void *semaphore_taker_task (__attribute__((unused)) void *arg)
+{
- sem_post (&sem);
+ while (try < nb_measurements) {
+ ts_t ts;
+ sys_timestamp (&ts);
+ sem_wait (&sem);
+ if (shared_flag) {
+ sys_timestamp (&ts2);
+ if (diff_timestamp (&ts2, &ts) < (9 * TIMER / 10)) {
+ nbtoofast++;
+ } else {
+ deltas[try++] = diff_timestamp (&ts2, &ts1);
+ }
+ shared_flag = 0;
+ }
+ sem_post (&sem);
+ }
- return NULL;
+ pthread_exit (NULL);
}
int test (dts_t *buffer, int nb)
/* set global variables */
- measure_tab = buffer;
+ deltas = buffer;
+ nb_measurements = nb;
/* semaphore test */
sem_init (&sem, 0, 1);
- for (int i = 0; i < nb; i++) {
-
- //bzero (&tsi, sizeof (ts1));
+ shared_flag = 1;
- pthread_t tid1;
- if (pthread_create (&tid1, NULL, trythis, NULL) != 0) {
- fprintf (stderr, "error on pthread_create\n");
- return 1;
- }
-
- pthread_t tid2;
- if (pthread_create (&tid2, NULL, trythis, NULL) != 0) {
- fprintf (stderr, "error on pthread_create\n");
- return 1;
- }
+ pthread_t giver_thread;
+ if (pthread_create (&giver_thread, NULL, semaphore_giver_task, NULL) != 0) {
+ fprintf (stderr, "error on pthread_create for giver_task\n");
+ return 1;
+ }
- pthread_join (tid1, NULL);
- pthread_join (tid2, NULL);
+ pthread_t taker_thread;
+ if (pthread_create (&taker_thread, NULL, semaphore_taker_task, NULL) != 0) {
+ fprintf (stderr, "error on pthread_create for taker_task\n");
+ return 1;
}
+ pthread_join (giver_thread, NULL);
+ pthread_join (taker_thread, NULL);
+
sem_destroy (&sem);
+ printf ("Too fast: %d\n", nbtoofast);
+
return 0;
}