update chat

This commit is contained in:
mutouyun 2019-02-13 18:19:28 +08:00
parent 881f98c241
commit 75f5090d6a
2 changed files with 32 additions and 12 deletions

View File

@ -1,37 +1,56 @@
#include <iostream> #include <iostream>
#include <string> #include <string>
#include <thread> #include <thread>
#include <regex>
#include "ipc.h" #include "ipc.h"
namespace ipc {
namespace detail {
IPC_EXPORT std::size_t calc_unique_id();
} // namespace detail
} // namespace ipc
namespace { namespace {
char name__[] = "ipc-chat"; char name__[] = "ipc-chat";
char quit__[] = "q"; char quit__[] = "q";
char id__ [] = "c";
} // namespace } // namespace
int main() { int main() {
std::string buf; std::string buf, id = id__ + std::to_string(ipc::detail::calc_unique_id());
std::regex reg { "(c\\d+)> (.*)" };
ipc::channel cc { name__ }; ipc::channel cc { name__ };
std::thread r {[] { std::thread r {[&id, &reg] {
ipc::channel cc { name__ }; ipc::channel cc { name__ };
std::cout << id << " is ready." << std::endl;
while (1) { while (1) {
auto buf = cc.recv(); auto buf = cc.recv();
if (buf.empty()) continue; if (buf.empty()) continue;
std::string dat { static_cast<char const *>(buf.data()), buf.size() - 1 }; std::string dat { static_cast<char const *>(buf.data()), buf.size() - 1 };
if (dat == quit__) { std::smatch mid;
std::cout << "receiver quit..." << std::endl; if (std::regex_match(dat, mid, reg)) {
return; if (mid.str(1) == id) {
if (mid.str(2) == quit__) {
std::cout << "receiver quit..." << std::endl;
return;
}
continue;
}
} }
std::cout << "> " << dat << std::endl; std::cout << dat << std::endl;
} }
}}; }};
while (1) { while (1) {
std::cin >> buf; std::cin >> buf;
cc.send(buf); cc.send(id + "> " + buf);
if (buf == quit__) break; if (buf == quit__) break;
} }

View File

@ -37,7 +37,6 @@ public:
} }
bool post(long count = 1) { bool post(long count = 1) {
if (count <= 0) return true;
return !!::ReleaseSemaphore(h_, count, NULL); return !!::ReleaseSemaphore(h_, count, NULL);
} }
}; };
@ -116,10 +115,12 @@ public:
void broadcast(handle_t& h) { void broadcast(handle_t& h) {
if (h == invalid()) return; if (h == invalid()) return;
IPC_UNUSED_ auto guard = ipc::detail::unique_lock(mtx(h)); IPC_UNUSED_ auto guard = ipc::detail::unique_lock(mtx(h));
sem(h).post(counter_); if (counter_ > 0) {
while (counter_ > 0) { sem(h).post(counter_);
-- counter_; do {
han(h).wait(); -- counter_;
han(h).wait();
} while (counter_ > 0);
} }
} }
}; };