共享内存 3.0 进程锁 与 进程锁

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <wait.h>
#include <fcntl.h>
#include <string.h>
#include <signal.h>
#include <pthread.h>
#include <time.h>
#include <stdarg.h>
#include<sys/mman.h>
#include<semaphore.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/select.h>
#include <sys/shm.h>
#include <sys/sem.h>
#define RCH1 0x52434831
#define RCH2 0x52434832
#define RCH3 0x52434833
#define RCH4 0x52434834
#define RCH5 0x52434835

typedef  struct{

	pthread_mutex_t mutex;
	pthread_mutexattr_t mutexattr;

	int flag ;
	char buf[1];
}SHM;

创建共享内存并初始化锁:

#include"common.h"


SHM *shm = NULL;


int main()
{

	int id;
	int key=getpid();
	id=shmget(key,100,0666|IPC_CREAT);//创建共享内存,注意读写权限
	printf("id = %d\n",id);
	char buf[]="abcdefghijkl";
	shm=shmat(id,NULL,0);//获取共享内存起始地址
	pthread_mutexattr_init(&shm->mutexattr);
	pthread_mutexattr_setpshared(&shm->mutexattr,PTHREAD_PROCESS_SHARED);//第二个参数设置为进程锁,默认为线程锁
	pthread_mutex_init(&shm->mutex,&shm->mutexattr);

	memcpy(shm->buf,buf,sizeof(SHM));
	shm->flag=0;
	sleep(100);
	
    shmdt(shm);//与共享内存断开连接
    shmctl(id,IPC_RMID,NULL);//销毁共享内存

}

访问共享内存并打印flag:

#include"common.h"

SHM *shm = NULL;
int main(int argc,char*argv[])
{

		int id=atoi(argv[1]);
		shm=shmat(id,NULL,0);//获取共享内存起始地址

	while(1){		
		pthread_mutex_lock(&shm->mutex);//上锁
		printf("增加前:buf = %s,flag =%d\n",shm->buf,shm->flag++);
		sleep(1);
		shm->flag--;	
		printf("增加后:buf = %s,flag =%d\n",shm->buf,shm->flag);
		pthread_mutex_unlock(&shm->mutex);	//解锁
		sleep(1);

	}

}

 

 

注意编译的时候需要 -lpthread。

如果不加上锁,打印的结果flag就会出现 0,1,2 ....这些值,

加上锁之后,打印的flag只能为0;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值