ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Zig Thread Pool for Parallel Computation

Zig

Goal -- WPM

Ready
Exercise Algorithm Area
1const std = @import("std");
2
3const Allocator = std.mem.Allocator;
4
5const Task = struct {
6func: fn (allocator: Allocator, data: anytype) !void,
7data: anytype,
8};
9
10const ThreadPool = struct {
11allocator: Allocator,
12workers: []std.Thread,
13task_queue: std.ArrayList(Task),
14queue_mutex: std.Mutex,
15queue_cond: std.Condition,
16shutdown_requested: bool,
17
18pub fn init(allocator: Allocator, num_threads: usize) !ThreadPool {
19var workers = std.ArrayList(std.Thread).init(allocator);
20try workers.ensureTotalCapacity(num_threads);
21
22var task_queue = std.ArrayList(Task).init(allocator);
23try task_queue.ensureTotalCapacity(16);
24
25var pool = ThreadPool {
26.allocator = allocator,
27.workers = workers.items,
28.task_queue = task_queue,
29.queue_mutex = std.Mutex.init(),
30.queue_cond = std.Condition.init(),
31.shutdown_requested = false,
32};
33
34for (0..num_threads) |i|
35{
36const thread = try std.Thread.spawn(.{}, worker_thread, .{pool});
37try workers.append(thread);
38}
39pool.workers = workers.items;
40return pool;
41}
42
43pub fn deinit(self: *ThreadPool) void {
44self.shutdown();
45self.task_queue.deinit();
46self.workers.deinit();
47}
48
49fn worker_thread(pool: *ThreadPool) void {
50while (true) {
51self.queue_mutex.lock();
52while (self.task_queue.items.len == 0 and !self.shutdown_requested) {
53self.queue_cond.wait(&self.queue_mutex);
54}
55
56if (self.shutdown_requested and self.task_queue.items.len == 0) {
57self.queue_mutex.unlock();
58break;
59}
60
61const task = self.task_queue.pop();
62self.queue_mutex.unlock();
63
64task.func(self.allocator, task.data) catch |err| {
65std.debug.print("Task failed: {anyerr}\n", .{err});
66};
67}
68}
69
70pub fn submit(self: *ThreadPool, func: fn (allocator: Allocator, data: anytype) !void, data: anytype) !void {
71self.queue_mutex.lock();
72defer self.queue_mutex.unlock();
73
74try self.task_queue.append(.{ .func = func, .data = data });
75self.queue_cond.signal();
76}
77
78pub fn shutdown(self: *ThreadPool) void {
79self.queue_mutex.lock();
80self.shutdown_requested = true;
81self.queue_mutex.unlock();
82self.queue_cond.broadcast(); // Wake up all waiting threads
83
84// Wait for all worker threads to finish
85for (self.workers) |thread|
86{
87thread.join();
88}
89}
90};
91
92// Example task function
93fn process_number(allocator: Allocator, data: anytype) !void {
94const num = @ptrToInt(data) catch unreachable;
95std.debug.print("Processing number {d} on thread {d}\n", .{ num, std.Thread.getCurrentId() });
96std.time.sleep(50 * 1000);
97_ = num;
98}
99
100pub fn main() !void {
101var gpa = std.heap.GeneralPurposeAllocator(.{}){};
102defer _ = gpa.deinit();
103const allocator = gpa.allocator();
104
105var pool = try ThreadPool.init(allocator, 4);
106defer pool.deinit();
107
108const num_tasks = 20;
109for (0..num_tasks) |i|
110{
111// Pass the integer 'i' as a pointer to the task data
112try pool.submit(process_number, @intToPtr(*void, i));
113}
114
115std.debug.print("All tasks submitted. Waiting for completion...\n", .{});
116// Shutdown implicitly waits for tasks to complete
117pool.shutdown();
118std.debug.print("Thread pool shutdown complete.\n", .{});
119}
Algorithm description viewbox

Zig Thread Pool for Parallel Computation

Algorithm description:

This Zig code implements a basic thread pool. A thread pool is a collection of pre-created worker threads that can execute tasks concurrently. Instead of creating a new thread for each task, tasks are submitted to a queue and picked up by available threads in the pool. This reduces the overhead of thread creation and management, improving performance for applications with many short-lived tasks. It's commonly used in servers, game engines, and parallel processing applications.

Algorithm explanation:

The `ThreadPool` struct manages worker threads, a task queue, and synchronization primitives. `init` creates a specified number of worker threads, each running `worker_thread`. `worker_thread` loops, acquiring a mutex, waiting on a condition variable if the queue is empty (and shutdown is not requested), then dequeuing a `Task`. If shutdown is requested and the queue is empty, the thread exits. Otherwise, it executes the task's function. `submit` adds a task to the queue, locks the mutex, appends the task, unlocks, and signals the condition variable to wake a waiting worker. `shutdown` sets a flag, broadcasts to all workers to wake them up, and then `join`s each worker thread to ensure they have completed. The `Task` struct holds a function pointer and its associated data. Time complexity for submitting a task is O(1) amortized (due to `ArrayList` resizing). Task execution time depends on the task itself. Space complexity is O(N + T) where N is the number of threads and T is the maximum number of tasks in the queue.

Pseudocode:

Task struct: func (function pointer), data (anytype)
ThreadPool struct: allocator, workers (list of threads), task_queue (list of Tasks), queue_mutex, queue_cond, shutdown_requested (boolean)

init(allocator, num_threads):
  initialize workers list
  initialize task_queue list
  initialize mutex, condition variable, shutdown_requested = false
  for i from 0 to num_threads-1:
    spawn worker_thread(self)
    add thread to workers list
  return ThreadPool

deinit(self):
  call shutdown()
  deinitialize task_queue, workers

worker_thread(self):
  loop forever:
    lock queue_mutex
    while task_queue is empty AND not shutdown_requested:
      wait on queue_cond (releases mutex)
    
    if shutdown_requested AND task_queue is empty:
      unlock queue_mutex
      break loop
    
    task = pop task from task_queue
    unlock queue_mutex
    
    execute task.func(allocator, task.data)
    handle task execution errors

submit(self, func, data):
  lock queue_mutex
  append Task{func, data} to task_queue
  unlock queue_mutex
  signal queue_cond (wake one worker)

shutdown(self):
  lock queue_mutex
  set shutdown_requested = true
  unlock queue_mutex
  broadcast queue_cond (wake all workers)
  for each thread in workers:
    join thread