0

I understand task as task in C#, but this questions is not related to C#.

Let's say I have single thread and two tasks (both CPU-bound). I would like to run them concurrently, without running one of them at the expense of starving completely the other one. How this could be implemented without assuming the code will somehow cooperate?

Is it possible to set some kind of timeout (or instruction countdown) on CPU/OS level to freeze task with its entire stack, and run the other task in the same manner, then resume the first one and so on?

This question does not go to level of multitasking with threads. It is about multitasking within single, one, thread. Task is not the same as thread.

greenoldman
  • 1,533

2 Answers2

3

The feature you are looking for is "fibers," sometimes called "cooperative threads." A fiber has its own stack, but you switch them in-and-out of threads cooperatively. Any one fiber can call a function, typically called yield, and pass the fiber that they wish the computer to execute on this thread. Only one fiber executes at one time on a given thread, and nothing can stop it from executing involuntarily -- it needs to call a yield function to cooperatively give away control.

I'm not certain if C# has fiber support. Fibers were never very popular, and it seems like a feature which will raise a lot of challenges for a managed language. But that's the feature you're looking for.

How to do it without cooperation between the algorithms? That answer is easy: the sole entire purpose of threads is to do exactly the thing you want to do, because you need OS help to do it. Threads take advantage of a timer that fires at the OS level every few milliseconds, and their knowledge of how their stack is constructed to do the exact thing you want to do.

The reason OS libraries support threads is because you cannot do this on your own without either the cooperation of the OS (threads) or the cooperation of your other algorithms (fibers).

Robert Harvey
  • 200,592
Cort Ammon
  • 11,917
  • 3
  • 26
  • 35
1

No, that is not possible.

On the CPU/OS level, multitasking is executed on the level of threads. The OS gives time to various threads, but doesn't know about the (more granular) concept of tasks.