Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement several 'threads' running in only one thread

Lately I've been thinking: How do they implement several 'threads' in only one thread?

I mean, how they implement several parallel running pieces of code in only one thread? How they save the state of the 'thread', create an interrupt and pass the CPU to the next one?

I think that the Scala-actors implement this. But how?

This can be answered for JVM or C, it doesn't matter. I just really want to learn the theory of it.

like image 525
José Leal Avatar asked Mar 23 '11 09:03

José Leal


1 Answers

I think you are confusing coroutines and green threads here.

Coroutines give up the control when they are ready to do it, without any interruption, so question about interruption is irrelevant here. Scala actors are implemented as coroutines.

Green threads are user-mode threads implemented by virtual machine without use of native OS capabilities. Obviously, virtual machine can insert any instructions into the code being executed in order to check whether it need to switch to another thread.

like image 104
axtavt Avatar answered Sep 28 '22 07:09

axtavt