#include <iostream>
#include <iomanip>
#include <compare>
#include <thread>
#include <mutex>
#include <vector>
#include <chrono>
#include <string>
struct SpaceShip {
int i;
std::strong_ordering operator<=>(SpaceShip const& rhs) {
return i <=> rhs.i;
}
};
void spaceship(int a, int b) {
std::cout << "a: " << a << "\n";
std::cout << "b: " << b << "\n";
auto result = (a <=> b);
if (result < 0) std::cout << "a <=> b is negative\n";
if (result > 0) std::cout << "a <=> b is positive\n";
if (result == 0) std::cout << "a <=> b is equivalent\n";
}
std::mutex cout_mutex;
void print(int taskID, int i, int j) {
const std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << "Task i " << taskID << " i: " << i << " " << "j: " << j << "\n";
}
void hardTask(int taskID) {
constexpr int items = 100;
for (int i = 0; i < items; i++) {
for (int j = 0; j < items; j++) {
if (rand() % 1000 < 2)
print(taskID, i, j);
std::sin(i * j);
}
}
const std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << "Task " << taskID << " done\n";
}
void supercomputer() {
std::vector<std::thread> threadPool;
for (int i = 0; i < 32; i++)
threadPool.push_back(std::thread(hardTask, i));
for (auto& t : threadPool) {
t.join();
}
}
int game_done = 0;
std::string message;
std::mutex game_mutex;
void display_thread() {
while (!game_done) {
if (!message.empty()) {
std::cout << message << "\n";
const std::lock_guard<std::mutex> lock(game_mutex);
message.clear();
}
using namespace std::chrono_literals;
std::this_thread::sleep_for(1s);
}
}
void input_thread() {
while (!game_done) {
std::string input;
std::getline(std::cin, input);
if (input == "quit") {
const std::lock_guard<std::mutex> lock(game_mutex);
game_done = 1;
}
else if (!input.empty()) {
const std::lock_guard<std::mutex> lock(game_mutex);
message = input;
}
}
}
void game() {
std::thread display(display_thread);
std::thread input(input_thread);
input.join();
display.join();
}
int main() {
//spaceship(1, 3);
//spaceship(3, 1);
//spaceship(1, 1);
//spaceship(0, 0);
//supercomputer();
game();
return 0;
}
Comments