Skip to content

Commit

Permalink
Lottery scheduling code
Browse files Browse the repository at this point in the history
  • Loading branch information
remzi-arpacidusseau committed Aug 15, 2018
1 parent 5a51470 commit f83b83e
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ CPU Virtualization Chapters:
* Direct Execution
* CPU Scheduling
* Multi-level Feedback
* Lottery Scheduling
* [Lottery Scheduling](https://github.com/remzi-arpacidusseau/ostep-code/tree/master/cpu-sched-lottery)
* Multi-CPU Scheduling

Memory Virtualization Chapters:
Expand Down
21 changes: 21 additions & 0 deletions cpu-sched-lottery/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

## Proportional Share Scheduling

Code from OSTEP chapter [Scheduling: Proportional Share](http://pages.cs.wisc.edu/~remzi/OSTEP/cpu-sched-lottery.pdf).

Compile with:

```
prompt> gcc -o lottery lottery.c -Wall
```

Run like this:

```
./lottery 1 100
```

which uses random seed '1' to run a little lottery 100 different times.

Read the source code for details.

74 changes: 74 additions & 0 deletions cpu-sched-lottery/lottery.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

// global ticket count
int gtickets = 0;

struct node_t {
int tickets;
struct node_t *next;
};

struct node_t *head = NULL;

void insert(int tickets) {
struct node_t *tmp = malloc(sizeof(struct node_t));
assert(tmp != NULL);
tmp->tickets = tickets;
tmp->next = head;
head = tmp;
gtickets += tickets;
}

void print_list() {
struct node_t *curr = head;
printf("List: ");
while (curr) {
printf("[%d] ", curr->tickets);
curr = curr->next;
}
printf("\n");
}

int
main(int argc, char *argv[])
{
if (argc != 3) {
fprintf(stderr, "usage: lottery <seed> <loops>\n");
exit(1);
}
int seed = atoi(argv[1]);
int loops = atoi(argv[2]);
srandom(seed);

// populate list with some number of jobs, each
// with some number of tickets
insert(50);
insert(100);
insert(25);

print_list();

int i;
for (i = 0; i < loops; i++) {
int counter = 0;
int winner = random() % gtickets; // get winner
struct node_t *current = head;

// loop until the sum of ticket values is > the winner
while (current) {
counter = counter + current->tickets;
if (counter > winner)
break; // found the winner
current = current->next;
}
// current is the winner: schedule it...
print_list();
printf("winner: %d %d\n\n", winner, current->tickets);

}
return 0;
}

0 comments on commit f83b83e

Please sign in to comment.