| 1 |
#include <assert.h> |
| 2 |
#include <stdlib.h> |
| 3 |
|
| 4 |
#define LIST_LENGTH 10 |
| 5 |
|
| 6 |
struct node |
| 7 |
{ |
| 8 |
struct node *next; |
| 9 |
int val; |
| 10 |
}; |
| 11 |
|
| 12 |
int |
| 13 |
sum_nodes (struct node *head) |
| 14 |
{ |
| 15 |
int i = 0, sum = 0; |
| 16 |
|
| 17 |
#pragma acc parallel reduction(+:sum) present(head[:1]) |
| 18 |
{ |
| 19 |
for (; head != NULL; head = head->next) |
| 20 |
sum += head->val; |
| 21 |
} |
| 22 |
|
| 23 |
return sum; |
| 24 |
} |
| 25 |
|
| 26 |
void |
| 27 |
insert (struct node *head, int val) |
| 28 |
{ |
| 29 |
struct node *n = (struct node *) malloc (sizeof (struct node)); |
| 30 |
|
| 31 |
if (head->next) |
| 32 |
{ |
| 33 |
#pragma acc exit data detach(head->next) |
| 34 |
} |
| 35 |
|
| 36 |
n->val = val; |
| 37 |
n->next = head->next; |
| 38 |
head->next = n; |
| 39 |
|
| 40 |
#pragma acc enter data copyin(n[:1]) |
| 41 |
#pragma acc enter data attach(head->next) |
| 42 |
if (n->next) |
| 43 |
{ |
| 44 |
#pragma acc enter data attach(n->next) |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
void |
| 49 |
destroy (struct node *head) |
| 50 |
{ |
| 51 |
while (head->next != NULL) |
| 52 |
{ |
| 53 |
#pragma acc exit data detach(head->next) |
| 54 |
struct node * n = head->next; |
| 55 |
head->next = n->next; |
| 56 |
if (n->next) |
| 57 |
{ |
| 58 |
#pragma acc exit data detach(n->next) |
| 59 |
} |
| 60 |
#pragma acc exit data delete (n[:1]) |
| 61 |
if (head->next) |
| 62 |
{ |
| 63 |
#pragma acc enter data attach(head->next) |
| 64 |
} |
| 65 |
free (n); |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
int |
| 70 |
main () |
| 71 |
{ |
| 72 |
struct node list = { .next = NULL, .val = 0 }; |
| 73 |
int i; |
| 74 |
|
| 75 |
#pragma acc enter data copyin(list) |
| 76 |
|
| 77 |
for (i = 0; i < LIST_LENGTH; i++) |
| 78 |
insert (&list, i + 1); |
| 79 |
|
| 80 |
assert (sum_nodes (&list) == (LIST_LENGTH * LIST_LENGTH + LIST_LENGTH) / 2); |
| 81 |
|
| 82 |
destroy (&list); |
| 83 |
|
| 84 |
#pragma acc exit data delete(list) |
| 85 |
|
| 86 |
return 0; |
| 87 |
} |