threadpool map unordered
- User
threadpool map unordered
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
threadpool map unordered
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
A threadpool with unordered map functionality allows you to apply a function to multiple inputs concurrently, where the results can be collected in any order as they complete. Here are implementations in a few different languages:
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
def worker_function(x):
# Simulate some work
time.sleep(x * 0.1)
return x * x
# Using ThreadPoolExecutor with as_completed for unordered results
def threadpool_map_unordered(func, iterable, max_workers=4):
with ThreadPoolExecutor(max_workers=max_workers) as executor:
# Submit all tasks
future_to_input = {executor.submit(func, item): item for item in iterable}
# Yield results as they complete (unordered)
for future in as_completed(future_to_input):
yield future.result()
# Usage
inputs = [3, 1, 4, 1, 5, 9, 2, 6]
results = list(threadpool_map_unordered(worker_function, inputs))
print(results) # Results in completion order, not input order
#include <future>
#include <vector>
#include <algorithm>
#include <chrono>
#include <thread>
template<typename Func, typename Iterator>
auto threadpool_map_unordered(Func func, Iterator begin, Iterator end) {
using ReturnType = decltype(func(*begin));
std::vector<std::future<ReturnType>> futures;
std::vector<ReturnType> results;
// Launch async tasks
for (auto it = begin; it != end; ++it) {
futures.push_back(std::async(std::launch::async, func, *it));
}
// Collect results as they complete
while (!futures.empty()) {
for (auto it = futures.begin(); it != futures.end();) {
if (it->wait_for(std::chrono::seconds(0)) == std::future_status::ready) {
results.push_back(it->get());
it = futures.erase(it);
} else {
++it;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return results;
}
use tokio::task;
use futures::future::join_all;
async fn worker_function(x: i32) -> i32 {
tokio::time::sleep(tokio::time::Duration::from_millis((x * 100) as u64)).await;
x * x
}
async fn threadpool_map_unordered<T, F, Fut>(
items: Vec<T>,
func: F
) -> Vec<F::Output>
where
F: Fn(T) -> Fut + Send + Sync + 'static,
Fut: std::future::Future + Send + 'static,
T: Send + 'static,
F::Output: Send + 'static,
{
let tasks: Vec<_> = items
.into_iter()
.map(|item| task::spawn(func(item)))
.collect();
// This waits for all to complete, but you could use select! for true unordered processing
let results = join_all(tasks).await;
results.into_iter().map(|r| r.unwrap()).collect()
}
The unordered approach is particularly useful when:
The main difference from ordered mapping is that faster tasks don't get blocked waiting for slower ones to complete first.