共有メモリを使用する: 共有するデータにメモリを割り当て、ロックを処理するミューテックス変数に 2 番目のセグメントを割り当てます。
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
}