并行创建多个 child 个进程 运行
Creating multiple child processes running parallel
我是这个 child parent 流程的新手。我喜欢创建一个 Master 和 3 个 slave。那些是同一回事吗?如果我创建 3 个 childs 会像 3 个奴隶吗?我的另一个问题是我已经创建了 3 childs。但我坚信这些 child 过程不是 运行 并行的。我必须让它们 运行 平行。我相信这个 for 循环不允许它?我还有什么其他方法可以实现三个奴隶 运行ning 并行并以随机顺序完成他们的工作?我实现它的方式,总是像从属 1 完成,然后从属 2 完成。但是我的教授问我他们应该能够随机完成。我认为我的代码 child 进程会在前面的 child 代码完成后创建另一个 child。
for(int i=0; i<3; i++){
pid_t slave = fork();
if (slave==0) /* only execute this if child */
{
std::cout << "Slave " << i+1 << ": ";
switch(i+1){
case 1 :
std::cout << "Project statistics" << std::endl;
break;
case 2 :
std::cout << "Midterm statistics" << std::endl;
break;
case 3 :
std::cout << "Final statistics" << std::endl;
break;
default :
std::cout << "Something Went Wrong" << std::endl;
}
foo("Child");
std::cout << "Slave " << i+1 << ": Done" << std::endl;
exit(0);
}
wait(&status); /* only the parent waits */
}
您需要删除 wait(&status)
才能使其并行工作(这将在 child 产生另一个 child 之前)。然后在最后添加另一个循环来获取状态。
即代码应该是
for (int i=0; i<3; i++) {
pid_t slave = fork();
if (slave==0) /* only execute this if child */
{
std::cout << "Slave " << i+1 << ": ";
switch (i+1) {
case 1 :
std::cout << "Project statistics" << std::endl;
break;
case 2 :
std::cout << "Midterm statistics" << std::endl;
break;
case 3 :
std::cout << "Final statistics" << std::endl;
break;
default :
std::cout << "Something Went Wrong" << std::endl;
}
foo("Child");
std::cout << "Slave " << i+1 << ": Done" << std::endl;
exit(0);
}
}
for (int i=0; i<3; i++) {
wait(&status);
}
我是这个 child parent 流程的新手。我喜欢创建一个 Master 和 3 个 slave。那些是同一回事吗?如果我创建 3 个 childs 会像 3 个奴隶吗?我的另一个问题是我已经创建了 3 childs。但我坚信这些 child 过程不是 运行 并行的。我必须让它们 运行 平行。我相信这个 for 循环不允许它?我还有什么其他方法可以实现三个奴隶 运行ning 并行并以随机顺序完成他们的工作?我实现它的方式,总是像从属 1 完成,然后从属 2 完成。但是我的教授问我他们应该能够随机完成。我认为我的代码 child 进程会在前面的 child 代码完成后创建另一个 child。
for(int i=0; i<3; i++){
pid_t slave = fork();
if (slave==0) /* only execute this if child */
{
std::cout << "Slave " << i+1 << ": ";
switch(i+1){
case 1 :
std::cout << "Project statistics" << std::endl;
break;
case 2 :
std::cout << "Midterm statistics" << std::endl;
break;
case 3 :
std::cout << "Final statistics" << std::endl;
break;
default :
std::cout << "Something Went Wrong" << std::endl;
}
foo("Child");
std::cout << "Slave " << i+1 << ": Done" << std::endl;
exit(0);
}
wait(&status); /* only the parent waits */
}
您需要删除 wait(&status)
才能使其并行工作(这将在 child 产生另一个 child 之前)。然后在最后添加另一个循环来获取状态。
即代码应该是
for (int i=0; i<3; i++) {
pid_t slave = fork();
if (slave==0) /* only execute this if child */
{
std::cout << "Slave " << i+1 << ": ";
switch (i+1) {
case 1 :
std::cout << "Project statistics" << std::endl;
break;
case 2 :
std::cout << "Midterm statistics" << std::endl;
break;
case 3 :
std::cout << "Final statistics" << std::endl;
break;
default :
std::cout << "Something Went Wrong" << std::endl;
}
foo("Child");
std::cout << "Slave " << i+1 << ": Done" << std::endl;
exit(0);
}
}
for (int i=0; i<3; i++) {
wait(&status);
}