summaryrefslogtreecommitdiffstats
path: root/media/libcubeb/src/cubeb_array_queue.h
blob: d6d95813251ed3463f6eee41afa2114ecfd26589 (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
 * Copyright © 2016 Mozilla Foundation
 *
 * This program is made available under an ISC-style license.  See the
 * accompanying file LICENSE for details.
 */

#ifndef CUBEB_ARRAY_QUEUE_H
#define CUBEB_ARRAY_QUEUE_H

#include <assert.h>
#include <pthread.h>
#include <unistd.h>

#if defined(__cplusplus)
extern "C" {
#endif

typedef struct {
  void ** buf;
  size_t num;
  size_t writePos;
  size_t readPos;
  pthread_mutex_t mutex;
} array_queue;

array_queue *
array_queue_create(size_t num)
{
  assert(num != 0);
  array_queue * new_queue = (array_queue *)calloc(1, sizeof(array_queue));
  new_queue->buf = (void **)calloc(1, sizeof(void *) * num);
  new_queue->readPos = 0;
  new_queue->writePos = 0;
  new_queue->num = num;

  pthread_mutex_init(&new_queue->mutex, NULL);

  return new_queue;
}

void
array_queue_destroy(array_queue * aq)
{
  assert(aq);

  free(aq->buf);
  pthread_mutex_destroy(&aq->mutex);
  free(aq);
}

int
array_queue_push(array_queue * aq, void * item)
{
  assert(item);

  pthread_mutex_lock(&aq->mutex);
  int ret = -1;
  if (aq->buf[aq->writePos % aq->num] == NULL) {
    aq->buf[aq->writePos % aq->num] = item;
    aq->writePos = (aq->writePos + 1) % aq->num;
    ret = 0;
  }
  // else queue is full
  pthread_mutex_unlock(&aq->mutex);
  return ret;
}

void *
array_queue_pop(array_queue * aq)
{
  pthread_mutex_lock(&aq->mutex);
  void * value = aq->buf[aq->readPos % aq->num];
  if (value) {
    aq->buf[aq->readPos % aq->num] = NULL;
    aq->readPos = (aq->readPos + 1) % aq->num;
  }
  pthread_mutex_unlock(&aq->mutex);
  return value;
}

size_t
array_queue_get_size(array_queue * aq)
{
  pthread_mutex_lock(&aq->mutex);
  ssize_t r = aq->writePos - aq->readPos;
  if (r < 0) {
    r = aq->num + r;
    assert(r >= 0);
  }
  pthread_mutex_unlock(&aq->mutex);
  return (size_t)r;
}

#if defined(__cplusplus)
}
#endif

#endif // CUBE_ARRAY_QUEUE_H