File size: 2,616 Bytes
b27bfb3 | 1 2 3 4 5 | {"type": "session", "harness": "opencode", "id": "cpp-concurrency-threads", "name": "Use C++ threads, mutexes, condition variables, and atomics"}
{"type": "message", "message": {"role": "system", "content": "You are an expert C++ developer. You write clean, efficient, and idiomatic code."}}
{"type": "message", "message": {"role": "user", "content": "Use C++ threads, mutexes, condition variables, and atomics"}}
{"type": "message", "message": {"role": "assistant", "content": "#include <thread>\n#include <mutex>\n#include <condition_variable>\n#include <atomic>\n#include <vector>\n#include <queue>\n#include <iostream>\n#include <functional>\n\nclass ThreadPool {\n std::vector<std::thread> workers;\n std::queue<std::function<void()>> tasks;\n std::mutex queue_mutex;\n std::condition_variable condition;\n bool stop = false;\npublic:\n explicit ThreadPool(size_t threads) {\n for (size_t i = 0; i < threads; ++i) {\n workers.emplace_back([this] {\n while (true) {\n std::function<void()> task;\n {\n std::unique_lock lock(queue_mutex);\n condition.wait(lock, [this] { return stop || !tasks.empty(); });\n if (stop && tasks.empty()) return;\n task = std::move(tasks.front());\n tasks.pop();\n }\n task();\n }\n });\n }\n }\n\n template<class F>\n void enqueue(F&& f) {\n {\n std::lock_guard lock(queue_mutex);\n tasks.emplace(std::forward<F>(f));\n }\n condition.notify_one();\n }\n\n ~ThreadPool() {\n {\n std::lock_guard lock(queue_mutex);\n stop = true;\n }\n condition.notify_all();\n for (auto& worker : workers) worker.join();\n }\n};\n\nint main() {\n // Atomics\n std::atomic<int> counter{0};\n std::vector<std::thread> threads;\n\n for (int i = 0; i < 10; ++i) {\n threads.emplace_back([&counter] {\n for (int j = 0; j < 1000; ++j) counter.fetch_add(1, std::memory_order_relaxed);\n });\n }\n for (auto& t : threads) t.join();\n std::cout << \"Counter: \" << counter.load() << \"\\n\";\n\n // Thread pool\n ThreadPool pool(4);\n for (int i = 0; i < 8; ++i) {\n pool.enqueue([i] {\n std::cout << \"Task \" << i << \" from thread \"\n << std::this_thread::get_id() << \"\\n\";\n });\n }\n\n return 0;\n}"}}
|