- 无缘进程间同步,本来打算使用有名信号量进行同步,但是有名信号量的初始化会受进程启动顺序影响,故使用共享内存进行封装,封装后的使用方法类似二值信号量,代码如下:
1 #include <sys/ipc.h> //ipc:inter-process communication进程通信 2 #include <sys/shm.h> //shm:share memory共享内存 3 #include <stdio.h> 4 #include <string> 5 6 typedef enum 7 { 8 YUV_CAP_END=1000, 9 YUV_READ_END, 10 VENC_END, 11 AENC_END, 12 }SHM_KEY; 13 14 class shm 15 { 16 private: 17 /* data */ 18 int shmid_; 19 unsigned char *pshm_ = NULL; 20 public: 21 void init(SHM_KEY key, unsigned char init_val){ 22 shmid_ = shmget(key, 4, IPC_CREAT | 0666); 23 if(shmid_ == -1) 24 { 25 printf("shmget failed\n"); 26 } 27 pshm_ = (unsigned char *)shmat(shmid_, 0, 0); 28 memset(pshm_, 0, 4); 29 pshm_[0] = init_val; 30 }; 31 32 void wait() 33 { 34 while (pshm_[0] == 0); 35 pshm_[0] = 0; 36 } 37 38 unsigned char get() 39 { 40 return pshm_[0]; 41 } 42 43 void notify() 44 { 45 if (pshm_[0] != 1) 46 pshm_[0] = 1; 47 } 48 49 void release() 50 { 51 shmdt(pshm_); 52 shmctl(shmid_, IPC_RMID, NULL); 53 } 54 55 explicit shm(SHM_KEY key, unsigned char init_val) { 56 init(key, init_val); 57 }; 58 59 shm()= delete; 60 ~shm(){ 61 release(); 62 }; 63 };
- 也可以创建两个对象,作为生产-消费模式的同步使用,伪代码如下:
1 shm shm_yuv_cap(YUV_CAP_END, 0); 2 shm shm_yuv_read(YUV_READ_END, 1); 3 4 shm_yuv_read.wait(); 5 生产数据; 6 shm_yuv_cap.notify();
1 shm shm_yuv_cap(YUV_CAP_END, 0); 2 shm shm_yuv_read(YUV_READ_END, 1); 3 4 shm_yuv_read.wait(); 5 消费数据; 6 shm_yuv_cap.notify();
标签:END,YUV,pshm,C++,yuv,init,linux,共享内存,shm From: https://www.cnblogs.com/aheng365/p/18397261