使用共享内存:为要共享的数据分配内存,并为互斥变量分配第二个段以处理锁定。
共享 float[9] 的示例代码:
服务器
int shmid, shmid_mutex;
key_t key = 1337, key_mutex = 1338;
float *shm;
pthread_mutex_t *shm_mutex;
int SHMSZ = sizeof(float[9]), SHMSZ_mutex = sizeof(pthread_mutex_t);
//Mutex shared memory
shmid_mutex = shmget(key_mutex, SHMSZ_mutex, IPC_CREAT | 0660); //Create the segment
shm_mutex = (pthread_mutex_t *)shmat(shmid_mutex, NULL, 0); //Attach the segment to data space
shmctl(shmid_mutex, SHM_LOCK, (struct shmid_ds *) NULL); //Lock this segment from being swapped
//Setup mutex attributes
pthread_mutexattr_t psharedm;
pthread_mutexattr_init(&psharedm);
pthread_mutexattr_setpshared(&psharedm, PTHREAD_PROCESS_SHARED);
//Initialize mutex
pthread_mutex_init(shm_mutex, &psharedm);
//Float array shared memory
shmid = shmget(key, SHMSZ, IPC_CREAT | 0660); //Create the segment
shm = (float *)shmat(shmid, NULL, 0); //Attach the segment to data space
shmctl(shmid, SHM_LOCK, (struct shmid_ds *) NULL); //Lock this segment from being swapped
float x = 0.1;
while(true)
{
pthread_mutex_lock(shm_mutex); //start critical section
//Write to shared memory
for (int i = 0; i < 9; i++)
shm[i] = x * i;
x += 0.1;
printf("W ");
for (int i = 0; i < 9; i++)
printf("%f ", shm[i]);
printf("\n");
usleep(100000); //slow down output to make it readable
pthread_mutex_unlock(shm_mutex); //end critical section
usleep(10000); //wait for 10ms to simulate other calculations
}
客户
int shmid, shmid_mutex;
key_t key = 1337, key_mutex = 1338;
float *shm;
pthread_mutex_t *shm_mutex;
int SHMSZ = sizeof(float[9]), SHMSZ_mutex = sizeof(pthread_mutex_t);
//Mutex shared memory
shmid_mutex = shmget(key_mutex, SHMSZ_mutex, IPC_CREAT | 0660); //Create the segment
shm_mutex = (pthread_mutex_t *)shmat(shmid_mutex, NULL, 0); //Attach the segment to data space
shmctl(shmid_mutex, SHM_LOCK, (struct shmid_ds *) NULL); //Lock this segment from being swapped
//Float array shared memory
shmid = shmget(key, SHMSZ, 0660); //Locate the segment
shm = (float *)shmat(shmid, NULL, 0); //Attach the segment to data space
shmctl(shmid, SHM_LOCK, (struct shmid_ds *) NULL); //Lock this segment from being swapped
while(true)
{
pthread_mutex_lock(shm_mutex); //start critical section
//Read from shared memory
printf("R ");
for (int i = 0; i < 9; i++)
printf("%f ", shm[i]);
printf("\n");
usleep(100000); //slow down output to make it readable
pthread_mutex_unlock(shm_mutex); //end critical section
usleep(10000); //wait for 10ms to simulate other calculations
}