Add mutex

This commit is contained in:
Inex Code 2021-03-30 16:47:22 +00:00
parent 9cd23555a6
commit 26c88bb65f

View file

@ -5,6 +5,7 @@
#include <chrono> #include <chrono>
#include <boost/asio.hpp> #include <boost/asio.hpp>
#include <boost/array.hpp> #include <boost/array.hpp>
#include <mutex>
using namespace std; using namespace std;
@ -96,6 +97,8 @@ ECmd cmd = ENone;
int counter = 0; int counter = 0;
std::mutex mtx;
float targetH = 10.; float targetH = 10.;
float getHZadFromUser() float getHZadFromUser()
@ -240,9 +243,9 @@ int model()
while (cmd != EExit) while (cmd != EExit)
{ {
mtx.lock();
hZad = targetH; // Неблокирующая функция для получения высоты hZad = targetH; // Неблокирующая функция для получения высоты
mtx.unlock();
if (abs(superpooh.getH() - hZad) < 1 && abs(t - lastT) > 5) { if (abs(superpooh.getH() - hZad) < 1 && abs(t - lastT) > 5) {
superpooh.eat(0.1); superpooh.eat(0.1);
lastT = t; lastT = t;
@ -277,15 +280,12 @@ int main() {
boost::asio::ip::udp::socket socket(io_context, reciever); boost::asio::ip::udp::socket socket(io_context, reciever);
std::thread th(model); std::thread th(model);
char ch;
while (cmd != EExit) while (cmd != EExit)
{ {
boost::array<char, 1> recv_b; boost::array<char, 1> recv_b;
boost::asio::ip::udp::endpoint remote_endpoint; boost::asio::ip::udp::endpoint remote_endpoint;
size_t len = socket.receive_from(boost::asio::buffer(recv_b), remote_endpoint); size_t len = socket.receive_from(boost::asio::buffer(recv_b), remote_endpoint);
ch = *(recv_b.data());
std::cout.write(recv_b.data(), len); std::cout.write(recv_b.data(), len);
std::cout << ch << std::endl;
if (*recv_b.data() == 'q') { if (*recv_b.data() == 'q') {
std::cout << "Exiting!" << std::endl; std::cout << "Exiting!" << std::endl;
cmd = EExit; cmd = EExit;
@ -293,11 +293,15 @@ int main() {
} }
if (*recv_b.data() == 'd') { if (*recv_b.data() == 'd') {
std::cout << "Going down!" << std::endl; std::cout << "Going down!" << std::endl;
mtx.lock();
targetH = 0.; targetH = 0.;
mtx.unlock();
} }
if (*recv_b.data() == 'u') { if (*recv_b.data() == 'u') {
std::cout << "Going up to 30 meters!" << std::endl; std::cout << "Going up to 30 meters!" << std::endl;
mtx.lock();
targetH = 30.; targetH = 30.;
mtx.unlock();
} }
} }
} }