1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18#include <stdlib.h>
19#include <stdio.h>
20#include <string.h>
21#include <unistd.h>
22#include <inttypes.h>
23#include <pthread.h>
24
25
26static inline int atomic_inc32(volatile int *x)
27{
28 int old, dummy;
29 __asm__ __volatile__(
30 "1: %0 = memw_locked(%2)\n\t"
31 " %1 = add(%0, #1)\n\t"
32 " memw_locked(%2, p0) = %1\n\t"
33 " if (!p0) jump 1b\n\t"
34 : "=&r"(old), "=&r"(dummy)
35 : "r"(x)
36 : "p0", "memory");
37 return old;
38}
39
40
41static inline long long atomic_inc64(volatile long long *x)
42{
43 long long old, dummy;
44 __asm__ __volatile__(
45 "1: %0 = memd_locked(%2)\n\t"
46 " %1 = #1\n\t"
47 " %1 = add(%0, %1)\n\t"
48 " memd_locked(%2, p0) = %1\n\t"
49 " if (!p0) jump 1b\n\t"
50 : "=&r"(old), "=&r"(dummy)
51 : "r"(x)
52 : "p0", "memory");
53 return old;
54}
55
56
57static inline int atomic_dec32(volatile int *x)
58{
59 int old, dummy;
60 __asm__ __volatile__(
61 "1: %0 = memw_locked(%2)\n\t"
62 " %1 = add(%0, #-1)\n\t"
63 " memw_locked(%2, p0) = %1\n\t"
64 " if (!p0) jump 1b\n\t"
65 : "=&r"(old), "=&r"(dummy)
66 : "r"(x)
67 : "p0", "memory");
68 return old;
69}
70
71
72static inline long long atomic_dec64(volatile long long *x)
73{
74 long long old, dummy;
75 __asm__ __volatile__(
76 "1: %0 = memd_locked(%2)\n\t"
77 " %1 = #-1\n\t"
78 " %1 = add(%0, %1)\n\t"
79 " memd_locked(%2, p0) = %1\n\t"
80 " if (!p0) jump 1b\n\t"
81 : "=&r"(old), "=&r"(dummy)
82 : "r"(x)
83 : "p0", "memory");
84 return old;
85}
86
87#define LOOP_CNT 1000
88
89volatile int tick32 = 1;
90
91volatile long long tick64 = 1;
92int err;
93
94void *thread1_func(void *arg)
95{
96 int i;
97
98 for (i = 0; i < LOOP_CNT; i++) {
99 atomic_inc32(&tick32);
100 atomic_dec64(&tick64);
101 }
102 return NULL;
103}
104
105void *thread2_func(void *arg)
106{
107 int i;
108 for (i = 0; i < LOOP_CNT; i++) {
109 atomic_dec32(&tick32);
110 atomic_inc64(&tick64);
111 }
112 return NULL;
113}
114
115void test_pthread(void)
116{
117 pthread_t tid1, tid2;
118
119 pthread_create(&tid1, NULL, thread1_func, "hello1");
120 pthread_create(&tid2, NULL, thread2_func, "hello2");
121 pthread_join(tid1, NULL);
122 pthread_join(tid2, NULL);
123
124 if (tick32 != 1) {
125 printf("ERROR: tick32 %d != 1\n", tick32);
126 err++;
127 }
128 if (tick64 != 1) {
129 printf("ERROR: tick64 %lld != 1\n", tick64);
130 err++;
131 }
132}
133
134int main(int argc, char **argv)
135{
136 test_pthread();
137 puts(err ? "FAIL" : "PASS");
138 return err;
139}
140