-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnewfile2.cpp
More file actions
107 lines (87 loc) · 2.85 KB
/
Copy pathnewfile2.cpp
File metadata and controls
107 lines (87 loc) · 2.85 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <iostream>
#include <thread>
#include <mutex>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#include <atomic>
// Function to set terminal attributes for macOS input handling
void setTerminalAttributes() {
struct termios termAttr;
tcgetattr(STDIN_FILENO, &termAttr);
termAttr.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &termAttr);
}
// Function to restore terminal attributes on macOS
void restoreTerminalAttributes() {
struct termios termAttr;
tcgetattr(STDIN_FILENO, &termAttr);
termAttr.c_lflag |= ICANON | ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &termAttr);
}
std::mutex mtx; // Mutex for protecting the shared variable
std::unique_lock<std::mutex> lock(mtx, std::defer_lock); // Create a unique_lock without acquiring the lock initially
int sharedVariable = 0; // Shared variable
std::atomic<bool> shouldExit(false); // Shared flag to signal thread to exit
void listenfks() {
while (shouldExit == false) {
char input;
if (read(STDIN_FILENO, &input, 1) != -1) {
if (input == 'q' || input == 'Q') {
lock.lock(); // Manually acquire the lock
sharedVariable = 3;
lock.unlock();
}
else if (input == 'p' || input == 'P') { // <-- Missing semicolon here
std::cout << "Paused! press 'c' to continue." << std::endl;
lock.lock(); // Manually acquire the lock
sharedVariable = 1;
lock.unlock();
while (true) {
if (read(STDIN_FILENO, &input, 1) != -1) {
if (input == 'c' || input == 'C') {
lock.lock(); // Manually acquire the lock
sharedVariable = 2;
lock.unlock();
break;
}
}
}
}
//std::cout << input << std::endl;
}
}
std::cout<<"Input listenfks terminated!"<<std::endl;
}
int main() {
// Create two threads
std::thread t1(listenfks);
setTerminalAttributes();
while(true){
if(sharedVariable == 1){
lock.lock(); // Manually acquire the lock
sharedVariable = 0;
lock.unlock();
while(true){
if(sharedVariable == 2){break;}
}
}
if(sharedVariable == 3){ // 3 is code for quit
lock.lock();
sharedVariable = 0;
lock.unlock();
break;
}
//you application
//
std::cout<<"..."<<std::endl;
}
std::cout<<"Main loop is done!"<<std::endl;
// Signal the thread to exit
shouldExit = true;
restoreTerminalAttributes();
return 0;
// Wait for the threads to finish
t1.join();
}