最近写程序涉及到进程间内存共享与读写访问锁的问题。 写个测试用的小程序。可以很好的模拟。
主程序。testM。 申请一块共享内存。 通过信号量进行控制。快速读写。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <time.h>
#include <semaphore.h>
typedef struct pshare
{
sem_t sem;
int referMain;
int referS;
}st_pshare;
/* 主进程调用*/
int main()
{
/* 初始化共享内存*/
int shm_id;
int i= 0;
st_pshare *ps = NULL;
int ret = 0;
struct tm *t;
time_t tt3,tt4,tt,t2;
//创建共享内存
shm_id=shmget(33333,100,0640|IPC_CREAT);
if(shm_id==-1)
{
printf("create share mem shmget error\n");
return -1;
}
//共享内存附加到自己的内存段
ps =(st_pshare*)shmat(shm_id,NULL,0);
ps->referMain = 0;
ps->referS = 0;
ret = sem_init(&ps->sem,1,1);
if( ret != 0)
{
printf("sam_init erro.%d\n",ret);
}
time(&tt3);
for( i = 0;i<10000;i++)
{
time(&tt);
// printf("wait to sam area\n");
sem_wait(&ps->sem);
time(&t2);
// printf("--->into sam are.wait(s):%d\n",(t2-tt));
ps->referMain++;
usleep(1000);
// printf("referMain = %d, refers= %d\n",ps->referMain,ps->referS);
sem_post(&ps->sem);
// printf("<---out sam area,sleep 5\n");
}
time(&tt4);
printf("loop over exit,use time:%d\n",tt4-tt3);
return 0;
}
从进程。testS。 访问主程序申请的共享内存。 通过信号量进行控制。读写一块内存。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <time.h>
#include<semaphore.h>
typedef struct pshare
{
sem_t sem;
int referMain;
int referS;
}st_pshare;
/* 主进程调用*/
int main()
{
/* 初始化共享内存*/
int shm_id;
int i= 0;
st_pshare *ps = NULL;
int ret = 0;
struct tm *t;
time_t tt3,tt4,tt,t2;
//获取共享内存
shm_id=shmget(33333,100,0640);
if(shm_id==-1)
{
printf("create share mem shmget error\n");
return -1;
}
//共享内存附加到自己的内存段
ps =(st_pshare*)shmat(shm_id,NULL,0);
if ( ps == (void *)-1)
{
printf("get share mem erro");
return 0;
}
time(&tt3);
for(i = 0;i<10000;i++)
{
time(&tt);
// printf("wait to sam area\n");
sem_wait(&ps->sem);
time(&t2);
// printf("--->into sam are.wait(s):%d\n",(t2-tt));
ps->referS++;
ps->referMain++;
usleep(1000);
// printf("referMain = %d, refers= %d\n",ps->referMain,ps->referS);
sem_post(&ps->sem);
// printf("<---out sam area,sleep 3\n");
}
time(&tt4);
printf("loop over exit,use time:%d\n",tt4-tt3);
if (shmctl( shm_id , IPC_RMID , NULL ) == -1)
perror(" delete error ");
return 0;
}
编译:
gcc testm.c -o testm -lrt
gcc testsS.c -o testS -lrt
运行时先启动 testm,后启动testS.
程序执行耗时10s。 可以增加sleep时间并将注释打开,观察共享内存中数据更新情况。