Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <stdio.h>
- #include <sys/time.h>
- #include <time.h>
- #include <errno.h>
- #include <stdlib.h>
- pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
- pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
- int g_ms = -1;
- int iterations = 0;
- void waitMillis(int ms)
- {
- int n;
- struct timeval tv;
- struct timespec ts;
- gettimeofday(&tv, NULL);
- ts.tv_sec = time(NULL) + ms / 1000;
- ts.tv_nsec = tv.tv_usec * 1000 + 1000 * 1000 * (ms % 1000);
- ts.tv_sec += ts.tv_nsec / (1000 * 1000 * 1000);
- ts.tv_nsec %= (1000 * 1000 * 1000);
- pthread_mutex_lock(&mutex);
- n = pthread_cond_timedwait(&cond, &mutex, &ts);
- pthread_mutex_unlock(&mutex);
- if (n == 0) {
- printf("waitMillis: We were signalled!\n");
- } else if (n == ETIMEDOUT) {
- printf("waitMillis: We timed out!\n");
- }
- }
- void *threadRoutine(void *arg) {
- while (1) {
- waitMillis(g_ms);
- iterations++;
- printf("threadRoutine: Finished (%d)\n", iterations);
- }
- }
- int main(int argc, const char **argv) {
- pthread_t thread;
- int input, ms;
- if (argc < 2) {
- fprintf(stderr, "Error: Please pass milliseconds for our timer!\n");
- exit(-1);
- }
- ms = atoi(argv[1]);
- if (ms < 100) {
- fprintf(stderr, "Error: Pas at least 100ms!\n");
- exit(-1);
- }
- g_ms = ms;
- pthread_create(&thread, NULL, threadRoutine, NULL);
- while (1) {
- printf("Main: Enter a number\n");
- scanf(" %d", &input);
- if (input == 0) {
- printf("Main: Signalling thread...\n");
- pthread_cond_signal(&cond);
- } else {
- printf("Main: Not signalling\n");
- }
- }
- }
Add Comment
Please, Sign In to add comment