-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathexerex-countdown-timer-a.cpp
More file actions
92 lines (57 loc) · 1.56 KB
/
Copy pathexerex-countdown-timer-a.cpp
File metadata and controls
92 lines (57 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
COUNTDOWN TIMER
*/
#include <iostream>
#include <unistd.h>
#include <time.h>
#include <pthread.h>
using namespace std;
char* buffer = nullptr;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* funcUserInput(void*) {
cin.getline(buffer, 1024);
pthread_cond_signal(&cond);
pthread_exit(nullptr);
return nullptr;
}
/*
Return true if no timeout. Otherwise, return false.
*/
bool waitForTime(const int waitTime) {
int ret = 0;
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += waitTime;
pthread_mutex_lock(&mut);
ret = pthread_cond_timedwait(&cond, &mut, &ts);
pthread_mutex_unlock(&mut);
if (0 != ret) {
// if (ETIMEDOUT == ret) return false;
return false;
}
return true;
}
int main() {
constexpr int SECONDS = 5;
char buff[1024] = { 0 };
buffer = buff;
pthread_t tid;
int ret = 0;
cout << "You have " << SECONDS << " seconds to write anything you like in one line." << endl;
cout << "Press enter to start." << endl;
cin.getline(buffer, 1024);
cout << "START!!!" << endl << endl;
ret = pthread_create(&tid, nullptr, &funcUserInput, nullptr);
if (waitForTime(SECONDS)) {
cout << "\nYou completed before the deadline." << endl;
}
else {
ret = pthread_cancel(tid); // Kill thread
cout << "\n\nTIMEOUT!!!" << endl;
}
ret = pthread_join(tid, nullptr);
ret = pthread_mutex_destroy(&mut);
ret = pthread_cond_destroy(&cond);
return 0;
}