Skip to content

Instantly share code, notes, and snippets.

@dpapathanasiou
Last active December 26, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpapathanasiou/7fb9884aa315b682611a to your computer and use it in GitHub Desktop.
Save dpapathanasiou/7fb9884aa315b682611a to your computer and use it in GitHub Desktop.
Concurrency programming example: test user reflexes
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <pthread.h>
void *listen(void *timestamp) {
int c;
while((c = getc(stdin)) != EOF) {
if( c == '\n' ) {
gettimeofday((struct timeval *)timestamp, NULL);
break;
}
}
return NULL;
}
int main(void) {
pthread_t listener;
struct timeval entered, paused, diff;
if( pthread_create(&listener, NULL, listen, &entered) ) {
fprintf(stderr, "Error: could not create keyboard listening thread\n");
return 1;
}
srand(time(NULL));
sleep(rand() % 10 + 1);
printf("GO!\n");
gettimeofday(&paused, NULL);
if( pthread_join(listener, NULL) ) {
fprintf(stderr, "Error: could not join keyboard listening thread\n");
return 2;
}
if( timercmp(&paused, &entered, >) )
printf("FAIL\n");
else {
timersub(&entered, &paused, &diff);
printf("%ld\n", (1000LL * diff.tv_sec) + (diff.tv_usec / 1000));
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment