这是我的代码
#include <iostream>
#include <string>
#include <ctime>
int main()
{
for (int i=0;i<3;i++) {
if((pid()==fork())==0){
break;
}
}
if(pid==0) {
// son process
srand(time(NULL));
int r = rand()%4+1;
cout<<"pid:"<<getpid() <<"num": "<<r<<endl;
}
else{
//parent process
}
}
我遇到与所有进程相同的随机数问题,如何重置 rand()? 我已经尝试为每个进程创建不同的 srand() 它不起作用。
最佳答案
- 将
time(NULL)+getpid()
放入所有rand的不同种子中; - http://man7.org/linux/man-pages/man3/pthread_join.3.html
关于C++随机数并在处理时等待所有子级的父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43396669/