【发布时间】:2012-06-25 23:00:57
【问题描述】:
我有以下代码:
#include <stdio.h>
#include <pthread.h>
#define THREAD_CNT 10
#define ITER 100
#define PRINT 1
int lock;
unsigned long long int counter;
void spin_lock(int *p) {
while(!__sync_bool_compare_and_swap(p, 0, 1));
}
void spin_unlock(int volatile *p) {
asm volatile ("");
*p = 0;
}
void *exerciser(void *arg) {
unsigned long long int i;
int id = (int)arg;
for(i = 0; i < ITER; i++) {
spin_lock(&lock);
counter = counter + 1;
if(PRINT) {
printf("%d: Incrementing counter: %llu -> %llu\n", id, counter-1, counter);
}
spin_unlock(&lock);
}
pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
pthread_t thread[THREAD_CNT];
counter = 0;
int i;
for(i = 0; i < THREAD_CNT; i++) {
pthread_create(&thread[i], NULL, exerciser, (void *) i);
}
for(i = 0; i < THREAD_CNT; i++) {
pthread_join(thread[i], NULL);
}
printf("Sum: %llu\n", counter);
printf("Main: Program completed. Exiting.\n");
pthread_exit(NULL);
}
当PRINT被定义为1时,我最后得到了正确的计数器值:
7: Incrementing counter: 996 -> 997
7: Incrementing counter: 997 -> 998
7: Incrementing counter: 998 -> 999
7: Incrementing counter: 999 -> 1000
Sum: 1000
Main: Program completed. Exiting.
如果我将 PRINT 设为 0,我会得到以下结果(多次运行):
$ ./a.out
Sum: 991
Main: Program completed. Exiting.
$ ./a.out
Sum: 1000
Main: Program completed. Exiting.
$ ./a.out
Sum: 962
Main: Program completed. Exiting.
$ ./a.out
Sum: 938
Main: Program completed. Exiting.
对正在发生的事情有任何见解吗?为什么当我启用打印语句时,我的结果(始终)正确,但我禁用它并且我的计数器没有达到目标值?我使用过很多 pthread,但对直接使用自旋锁不是很有经验。
感谢任何帮助或反馈。
【问题讨论】: