source: CIVL/examples/compare/queue/queue_two_lock.c@ a389857

main test-branch
Last change on this file since a389857 was ea777aa, checked in by Alex Wilton <awilton@…>, 3 years ago

Moved examples, include, build_default.properties, common.xml, and README out from dev.civl.com into the root of the repo.

git-svn-id: svn://vsl.cis.udel.edu/civl/trunk@5704 fb995dde-84ed-4084-dfe6-e5aef3e2452c

  • Property mode set to 100644
File size: 1.9 KB
RevLine 
[57732bb5]1#ifndef _QUEUE_TWO_LOCK_
2#define _QUEUE_TWO_LOCK_
3
4#include <stdbool.h>
5#include <stdlib.h>
6#include "queue.h"
7
8typedef int lock_t;
9#define FREE 0
10#define lock(l) $when (l==0) l=1;
11#define unlock(l) l=0;
12
13typedef struct node_t {
14 int value;
15 struct node_t *next;
16} node_t;
17
18struct queue_t {
19 node_t *Head;
20 node_t *Tail;
21 lock_t H_lock;
22 lock_t T_lock;
23};
24
25void initialize(queue_t *Q) {
26 node_t *node = (node_t*)malloc(sizeof(node_t));
27
28 node->next = NULL; // Make it the only node in the linked list
29 Q->Head = Q->Tail = node; // Both Head and Tail point to it
30 Q->H_lock = Q->T_lock = FREE; // Locks are initially free
31}
32
33void enqueue(queue_t *Q, int value) {
34 node_t *node = (node_t*)malloc(sizeof(node_t)); // in root scope
35
36 node->value = value; // Copy enqueued value into node
37 node->next = NULL; // Set next pointer of node to NULL
38 lock(Q->T_lock); // Acquire T_lock in order to access Tail
39 Q->Tail->next = node; // Link node at the end of the linked list
40 Q->Tail = node; // Swing Tail to node
41 unlock(Q->T_lock); // Release T_lock
42}
43
44_Bool dequeue(queue_t *Q, int *pvalue) {
45 node_t *node, *new_head;
46
47 lock(Q->H_lock); // Acquire H_lock in order to access Head
48 node = Q->Head; // Read Head
49 new_head = node->next; // Read next pointer
50 if (new_head == NULL) { // Is queue empty?
51 unlock(Q->H_lock); // Release H_lock before return
52 return false; // Queue was empty
53 }
54 *pvalue = new_head->value; // Queue not empty. Read value before release
55 Q->Head = new_head; // Swing Head to next node
56 unlock(Q->H_lock); // Release H_lock
57 free(node); // Free node
58 return true; // Queue was not empty, dequeue succeeded
59}
60
61void freequeue(queue_t q){
62 free(q.Head);
63}
64
65#endif
Note: See TracBrowser for help on using the repository browser.