gpt4 book ai didi

c - 在 C 中使用共享内存添加数组元素

转载 作者:太空宇宙 更新时间:2023-11-04 02:55:28 26 4
gpt4 key购买 nike

我有一个项目来说明如何在 C 中使用共享内存。这是我建议的本学期项目作业:以特殊方式将二维数组中的所有元素相加:

  • take input from user the row size (m) and column size (n), for example m = 4, n = 3.
  • the program will be called, for example: myadder 9 8 7 3 2 1 2 3 4 2 10 12 (these 12 numbers input are separated by white-space or return key)
  • create a shared memory 1d array of enough size to hold the entire above 2d array
  • then, create a shared memory 1d array of the size of the number of rows m. This array will be used to store the totals of each of the rows after it is calculated
  • the program then fork off a child process for each row in the array. This child process will total up its associated row and only it's row from shared memory, and store result in its associated element in another 1d array, called total_row
  • The parent process will wait until all children have finished, then add up all elements in total_row.

你能给我提示以完成上述任务吗?

最佳答案

我相信这应该可以解决问题:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>

int main ()
{
int w, h, i, j;

/* Read the width and height */
scanf ("%d %d", &w, &h);

/* Create and read the entire array */
int *arr = malloc (w * h * sizeof (int));
for (i = 0; i < w * h; ++i)
scanf ("%d", &arr[i]);

/* Obtain a shared memory segment with the key 42 */
int shm = shmget (42, h * sizeof (int), IPC_CREAT | 0666);
if (shm < 0)
{
perror ("shmget");
return 1;
}

/* Attach the segment as an int array */
int *row = shmat (shm, NULL, 0);
if (row < (int *) NULL)
{
perror ("shmat");
return 1;
}

for (i = 0; i < h; ++i)
/* Create h children and make them work */
if (!fork ())
{
for (j = row[i] = 0; j < w; ++j)
row[i] += arr[i * w + j];
return 0;
}

/* Wait for the children to finish up */
for (i = 0; i < h; ++i)
wait (&j);

/* Sum the row totals */
for (i = j = 0; i < h; ++i)
j += row[i];

printf ("%d\n", j);

/* Detach the shared memory segment and delete its key for later reuse */
shmdt (row);
shmctl (shm, IPC_RMID, NULL);

free (arr);
return 0;
}

关于c - 在 C 中使用共享内存添加数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18071559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com