Last active
December 26, 2015 14:27
-
-
Save dpapathanasiou/7fb9884aa315b682611a to your computer and use it in GitHub Desktop.
Concurrency programming example: test user reflexes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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