📄 spinlock.c
字号:
#include<stdio.h>
#include<unistd.h>
#include <sys/shm.h>
#include <errno.h>
#include <memory.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#define LOCKED 1 /* spinlock is locked */
#define UNLOCKED 0 /* spinlock is free */
#define SPINLOCKS 3 /* the number of spinlocks */
#define TERMINATED 1 /* the process is terminated*/
#define UNTERMINATED 0 /*the process is still running or not yet started*/
int *lock[SPINLOCKS]; /*the lock*/
int *terminate[SPINLOCKS]; /*share lock */
int *lockTerminate[SPINLOCKS]; /*share lock lock*/
//get spinlock
int get_spinlock( int *lockarea )
{
asm(
"pushl %%eax;\n\t"
"pushl %%ecx;\n\t"
"l1: movl %1, %%eax;\n\t"
"movl %2, %%ecx;"
"cmpxchg %%ecx, %0;\n\t"
"jne l1;\n\t"
"popl %%ecx;\n\t"
"popl %%eax;\n\t"
: "+m" (*lockarea)
:"i"(UNLOCKED),"i"(LOCKED)
:"%eax","%ecx");
return 0;
}
int release_spinlock(int *lockarea)
{
*lockarea = UNLOCKED;
}
main()
{
int *shmptr;
int shmid, i;
int m_pid; //监控进程m的进程标识符
int p_pid;
int status;
/* Get shared memory to hold the data structures protected by
one or more spinlocks. 74285 is a unique key, 1024 is size */
shmid = shmget(74285, 3*SPINLOCKS*sizeof(int), IPC_CREAT|0600);
if (shmid == -1) {
fprintf(stderr, "shmget failed\n");
exit(EXIT_FAILURE);
}
shmptr = shmat(shmid, 0, 0); /* Attach to the阿 shared memory */
if ( shmptr == (void *)-1) {
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < 3* SPINLOCKS; i++)
{
shmptr[i]= 1;
}
for (i=0; i < SPINLOCKS; i++)
{
lock[i] = shmptr + i;
terminate[i] = shmptr + i + SPINLOCKS;
*terminate[i] = 0;
lockTerminate[i] = shmptr + i + 2*SPINLOCKS;
}
for (i=0; i < SPINLOCKS; i++)
{
if ( (p_pid=fork()) ==0 )
{
get_spinlock(lock[i]);
printf("process %d is running\n",i);
get_spinlock(lockTerminate[i]);
*terminate[i] = 1;
break;
}
}
if (p_pid > 0) {
i = 0;
while(i < SPINLOCKS)
{
if(*lock[i]==LOCKED) {
release_spinlock(lockTerminate[i]);
release_spinlock(lock[i]);
}
if (*terminate[i] == 1)
{
printf("process %d is terminated!\n",i);
i++;
}
}
wait(&status);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -