6

I'm working on a small c++-like language which I'll be compiling to LLVM. One of the things I want to implement is cooperative multitasking; there will be a "yield" operator which will hopefully switch the stack pointer and program counter to the next "thread" in my program.

Is it possible to do this in llvm? Can I set the stack pointer register? If not, is there anything else similar I can do?

Edit: LLVM coroutines (http://llvm.org/docs/Coroutines.html) sound promising, though https://internals.rust-lang.org/t/llvm-coroutines-to-bring-awarness/3708/12 brings up some questions regarding stackful or stackless coroutines. I wonder, can they be used to implement a general yield-like operator?

Edit 2: In c++ boost has something called a "context" which can implement stackful coroutines. Still trying to figure out how they do it though. Anyone know?

Verdagon
  • 2,456
  • 3
  • 22
  • 36

1 Answers1

-2

Assuming you have the gcd library available: You can easily implement cooperative multitasking by using a semaphore (dispatch_semaphore_t). The semaphore count is set up so that exactly one of your threads can run at the same time. The yield() function signals and immediately locks the semaphore - the signal() wakes up another thread, and the lock stops the thread that called yield.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • 2
    Oh interesting! This looks like it's an apple only thing though. Also, would this be as fast as swapping the stack pointer, or does this do something slow like going through the kernel? – Verdagon Sep 06 '16 at 02:39
  • 6
    I'd like to know how to get and set the stack pointer in LLVM IR, this doesn't answer the original question. – Vinnie Falco Jul 12 '18 at 22:41
  • Is there any update on this, I'm also looking for this. – harry Aug 10 '20 at 10:47
  • i found this helpful [https://stackoverflow.com/questions/29365198/how-to-use-llvm-intrinsics-llvm-read-register/29629920#29629920] – harry Aug 10 '20 at 11:23