summaryrefslogtreecommitdiff
path: root/Source/ExecutionEngine/ThreadTaskScheduler.cs
blob: 58c4c6d4fa618b72b76a4b96759ad4336e74c62c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Microsoft.Boogie
{
  // Implementation of System.Threading.Tasks.TaskScheduler which creates a unique thread per
  // task, and allows each thread to have its own custom stack size.  The standard
  // scheduler uses the .NET threadpool, which in turn inherits stack size from the EXE.
  public class ThreadTaskScheduler : TaskScheduler
  {
    private int stackSize;

    public ThreadTaskScheduler(int StackReserveSize)
    {
      Contract.Requires(StackReserveSize >= 0);

      stackSize = StackReserveSize;
    }

    protected override IEnumerable<Task> GetScheduledTasks() 
    {
      // There is never a queue of scheduled, but not running, tasks.  
      // So return an empty list.
      return new List<Task>();
    }

    protected override void QueueTask(Task task) 
    {
      // Each queued task runs on a newly-created thread with the required 
      // stack size.  The default .NET task scheduler is built on the .NET 
      // ThreadPool.  Its policy allows it to create thousands of threads 
      // if it chooses.
      //
      // Boogie creates tasks which in turn create tasks and wait on them.
      // So throttling tasks via a queue risks deadlock.

      Thread th = new Thread(TaskMain, stackSize);
      th.Start(task);
    }

    protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) 
    {
      return false;
    }

    private void TaskMain(object data) 
    {
      Task t = (Task)data;
      TryExecuteTask(t);
    }
  }
}