Skip to content

Chez-CPS: Implement threads that can use handlers of the main thread - #1415

Draft
martin-ilgner wants to merge 4 commits into
mainfrom
chez-cps/threads
Draft

Chez-CPS: Implement threads that can use handlers of the main thread#1415
martin-ilgner wants to merge 4 commits into
mainfrom
chez-cps/threads

Conversation

@martin-ilgner

Copy link
Copy Markdown
Contributor

*with many restrictions

@martin-ilgner

martin-ilgner commented Jul 31, 2026

Copy link
Copy Markdown
Contributor Author

Example Program:

extern type Thread
extern type ThreadBoundary

extern chezCPS """
; Block, Boundary -> b
(define (with-boundary prog b)
  (prog (make-meta-cont top-level-k
                        (gensym "thread")
                        (create-store)
                        (make-thread-boundary (thread-boundary-mutex b)
                                              (thread-boundary-rest b)))
        top-level-k))
"""

extern def fork[T](boundary: ThreadBoundary){p: => T} at async: Thread =
  chezCPS "(k (fork-thread (lambda () (with-boundary ${p} ${boundary}))) ks)"

extern def initializeThreadBoundary() at async: ThreadBoundary =
  chezCPS "(k (make-thread-boundary (make-mutex) ks) ks)"

extern def join(thread: Thread): Unit =
  chezCPS "(thread-join ${thread})"

// For debugging
extern def displayMetaCont() at async: Unit =
  chezCPS """
    (begin
      (display "Metacontinuation:\n")
      (display ks)
      (display "\n\n")
      (k (void) ks))
  """

// Rules:
// - Threads accessing a handler of the main thread have to pass a thread boundary
// - The same thread boundary has to be used by all threads that use this handler/part of the main thread metacontinuation
// - The handler HAS TO RESUME
// - the main thread has to join
def main(): Unit = {
  try {
    val boundary = initializeThreadBoundary()
    val t1 = fork(boundary){
      println("Thread 1")
      do emit("1")
      do emit("2")
      println("Thread 1 terminated!")
    }
    val t2 = fork(boundary){
      println("Thread 2")
      do emit("11")
      do emit("22")
    }
    // do emit("main")
    join(t1)
    join(t2)
    println("Joined!")
  } with emit[String] { x =>
    resume(())
    println(x)
  }
}

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

Successfully merging this pull request may close these issues.

1 participant