Spawn_state.c 1.35 KB
Newer Older
1
2
3
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
4
#include "Spawn_state.h"
5
6

pthread_mutex_t spawn_mutex;
7
pthread_cond_t spawn_cond;
8
int spawn_state;
9
int waiting_redistribution=0;
10
11
12

void init_spawn_state() {
  pthread_mutex_init(&spawn_mutex,NULL);
13
  pthread_cond_init(&spawn_cond,NULL);
14
  set_spawn_state(1,0); //FIXME First parameter is a horrible magical number
15
16
17
18
}

void free_spawn_state() {
  pthread_mutex_destroy(&spawn_mutex);
19
  pthread_cond_destroy(&spawn_cond);
20
21
22
23
24
}

int get_spawn_state(int is_async) {
  int value;
  if(is_async) {
25
    pthread_mutex_lock(&spawn_mutex);
26
    value = spawn_state;
27
    pthread_mutex_unlock(&spawn_mutex);
28
29
30
  } else {
    value = spawn_state;
  }
31
  return value;
32
33
34
35
36
37
38
39
40
41
42
}

void set_spawn_state(int value, int is_async) {
  if(is_async) {
    pthread_mutex_lock(&spawn_mutex);
    spawn_state = value;
    pthread_mutex_unlock(&spawn_mutex);
  } else {
    spawn_state = value;
  }
}
43
44

int wait_wakeup() {
45
  pthread_mutex_lock(&spawn_mutex);
46
47
48
49
50
  if(!waiting_redistribution) {
    waiting_redistribution=1;
    pthread_cond_wait(&spawn_cond, &spawn_mutex);
  }
  waiting_redistribution=0;
51
  pthread_mutex_unlock(&spawn_mutex);
52
53
54
55
  return get_spawn_state(1);
}

void wakeup() {
56
  pthread_mutex_lock(&spawn_mutex);
57
58
59
60
  if(waiting_redistribution) {
    pthread_cond_signal(&spawn_cond);
  }
  waiting_redistribution=1;
61
  pthread_mutex_unlock(&spawn_mutex);
62
}