Trying to write a planner. It is necessary that the two threads ( LoopGetTask and LoopExecTask ) run in parallel, but Thread.Sleep does not give the desired result (only one of the functions is executed). The impression is that Thread.Sleep affects both threads no matter where it is called

 public class Scheduler { private Thread ThrExecTask; private Thread ThrGetTask; private Queue<int> taskList = new Queue<int>(); public Scheduler() { work = false; ThrExecTask = new Thread(LoopExecTask); ThrGetTask = new Thread(LoopGetTask); ThrExecTask.Start(); ThrGetTask.Start(); } } private void LoopGetTask() { while(true) { //получить список задач... insert into taskList Thread.Sleep(20000); } } private void LoopExecTask() { while(true) { //выполнить задачу exec taskList.first Thread.Sleep(1000); } } } 
  • one
    Why did you decide that only one of the threads is running? And where do you synchronize access to a common variable? - Pavel Mayorov

1 answer 1

Whether threads run in parallel or not depends on the operating system and on the number of logical processors in the system. Usually, even if you have only one logical processor, the system takes control from one thread from time to time, and gives it to another, so the threads run almost parallel.

This you cannot control (and should not).

Thread.Sleep eliminates the thread for a while from this scheme: this thread is simply not selected for execution by the system of time sharing. It does not directly affect other flows. Unless indirectly, if other threads are waiting for this thread.

The illusion that threads behave "wrong" may be due to the fact that you use shared data ( taskList ) from different threads without synchronization. It is forbidden to do so.


For the correct implementation of the job queue, take a look here: Implementation of the Producer / Consumer pattern .