Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Recipe] Thread pool #57

Open
lassik opened this issue Aug 25, 2021 · 0 comments
Open

[Recipe] Thread pool #57

lassik opened this issue Aug 25, 2021 · 0 comments

Comments

@lassik
Copy link
Member

lassik commented Aug 25, 2021

Problem

I have a task queue and I want to split the work among multiple threads. There can be many more tasks than threads.

Solution

The mailbox library is Chicken only, but any other thread-safe queue could be used instead.

(import (srfi 18))
(cond-expand (chicken (import (mailbox))))

(define (map-iota proc n)
  (let loop ((new-list '()) (i 0))
    (if (= i n) (reverse new-list)
        (loop (cons (proc i) new-list) (+ i 1)))))

(define thread-pool-size (make-parameter 2))

(define (run-thread-pool thunks)
  (let ((mailbox (make-mailbox)))
    (define (worker)
      (let loop ()
        (let ((thunk (mailbox-receive! mailbox 0 (eof-object))))
          (unless (eof-object? thunk)
            (thunk)
            (loop)))))
    (define (index->thread-name i)
      (string (integer->char (+ i (char->integer #\A)))))
    (for-each (lambda (thunk) (mailbox-send! mailbox thunk))
              thunks)
    (let ((threads (map-iota (lambda (i)
                               (make-thread worker (index->thread-name i)))
                             (thread-pool-size))))
      (for-each thread-start! threads)
      (let loop ()
        (unless (mailbox-empty? mailbox)
          (thread-sleep! 0.1)
          (loop)))
      (for-each thread-join! threads))))

Credit: @lassik

Usage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant