30 #define LOOPS 1024 // 10000000 42 pthread_spinlock_t spinlock;
44 pthread_mutex_t mutex;
47 void *consumer(
void *ptr)
51 printf(
"Consumer TID %lu\n", (
unsigned long) ptr);
56 pthread_spin_lock(&spinlock);
58 pthread_mutex_lock(&mutex);
64 pthread_spin_unlock(&spinlock);
66 pthread_mutex_unlock(&mutex);
75 pthread_spin_unlock(&spinlock);
77 pthread_mutex_unlock(&mutex);
88 struct timeval tv1, tv2;
91 pthread_spin_init(&spinlock, 0);
93 pthread_mutex_init(&mutex, NULL);
97 klog(LOG_INFO,
"TEST 0");
99 printf(
"Locking without any contention...\n");
100 pthread_mutex_t contention_mutex;
101 pthread_mutex_init(&contention_mutex, 0);
102 pthread_mutex_lock(&contention_mutex);
103 printf(
"Acquired\n");
104 pthread_mutex_unlock(&contention_mutex);
105 printf(
"Released!\n");
107 klog(LOG_INFO,
"TEST 1");
109 printf(
"Creating a recursive lock!\n");
110 pthread_mutex_t recursive;
111 pthread_mutexattr_t attr;
112 pthread_mutexattr_init(&attr);
113 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
114 pthread_mutex_init(&recursive, &attr);
115 printf(
"Testing recursion...\n");
116 pthread_mutex_lock(&recursive);
117 pthread_mutex_lock(&recursive);
118 pthread_mutex_lock(&recursive);
119 printf(
"Locked OK, testing unlock...\n");
120 pthread_mutex_unlock(&recursive);
121 pthread_mutex_unlock(&recursive);
122 pthread_mutex_unlock(&recursive);
123 printf(
"Testing re-acquire...\n");
124 pthread_mutex_lock(&recursive);
127 klog(LOG_INFO,
"TEST 2");
128 printf(
"Locking with deadlock\n");
129 pthread_mutex_t deadlock_mutex;
131 pthread_mutex_init(&deadlock_mutex, 0);
132 i = pthread_mutex_lock(&deadlock_mutex);
133 printf(
"First lock: %d (%s)\n", i, strerror(errno));
134 i = pthread_mutex_lock(&deadlock_mutex);
135 if (errno != EDEADLK)
136 printf(
"Didn't get EDEADLK!\n");
137 printf(
"Second lock: %d (%s)\n", i, strerror(errno));
138 pthread_mutex_unlock(&deadlock_mutex);
141 for (i = 0; i < LOOPS; i++)
142 the_list.push_back(i);
145 gettimeofday(&tv1, NULL);
147 klog(LOG_INFO,
"TEST 3");
148 pthread_create(&thr1, NULL, consumer, (
void *) 1);
149 pthread_create(&thr2, NULL, consumer, (
void *) 2);
151 pthread_join(thr1, NULL);
152 pthread_join(thr2, NULL);
153 klog(LOG_INFO,
"TEST 4");
156 gettimeofday(&tv2, NULL);
158 if (tv1.tv_usec > tv2.tv_usec)
161 tv2.tv_usec += 1000000;
165 "Result - %ld.%ld\n", tv2.tv_sec - tv1.tv_sec,
166 tv2.tv_usec - tv1.tv_usec);
169 pthread_spin_destroy(&spinlock);
171 pthread_mutex_destroy(&mutex);