我如何使用这些功能? 我已全球宣布锁定。
pthread_spinlock_t lock;
此外,螺旋锁在本地初始化。
pthread_spin_init(&lock, 1); // non-zero as pshared for IPC
但现在我想锁定我的关键整数并增加它。 我有一个循环运行它的多个进程:
while(0 != pthread_spin_trylock(&lock));
criticalInt += 1;
pthread_spin_unlock(&lock);
为什么不起作用? 另外,如何使用以下功能?
pthread_spin_lock(&lock);
编辑:
for (i=0; i < NUM_CHILDREN; i++) {
pid[i] = fork();
if (pid[i] == -1) { return EXIT_FAILURE; }
if (pid[i] == 0) {
while (criticalInt < MAXCOUNT) {
pthread_spin_lock(&lock);
criticalInt += 1;
pthread_spin_unlock(&lock);
count++;
}
printf("Process %i counted %i\n", i, count);
}
如果MAXCOUNT为1000000,则会产生以下输出:
Process 3 counted 687858
Process 0 counted 815657
Process 1 counted 640191
Process 2 counted 744340
实际上,总结起来应该是1000000.但它们不是。
如果我完全删除锁定,我会得到类似的结果。