【发布时间】:2019-04-01 11:03:27
【问题描述】:
我正在编写一个程序,我想在其中为每个进程创建多个进程和多个线程。简而言之,我的程序创建了多个进程,每个进程创建了多个线程。
这是一个简短的sn-p代码:
void NormalityComponent::newThread(int thread_id){
std::cout << "New Thread [" << thread_id +1 << "] created in Component [" << name_component << "] with id " << std::this_thread::get_id() << std::endl;
timeSimulation();
std::cout << "Thread [" << thread_id +1 << "] in [" << name_component << "] with id " << std::this_thread::get_id() << " ends its simulation" << std::endl;
}
void NormalityComponent::timeSimulation(){
for (int i = 0; i < time_factor * TEMPORAL_PARAMETER; i++);
}
void NormalityComponent::startAnalysisMode3(){
//creation of a new process to simulate the Normality Component Analysis and a thread for each Instance.
pid_t pid = fork();
if (pid == 0){
//Child Process
std::cout << "New Normality Component ["<< name_component <<"] created with id " << getpid() << std::endl;
//Creation of instances
for(int i = 0; i < number_instances;i++){
v_threads.push_back(std::thread(&NormalityComponent::newThread,this, i));
std::this_thread::sleep_for (std::chrono::milliseconds(100));
}
std::for_each(v_threads.begin(), v_threads.end(), std::mem_fn(&std::thread::join));
kill(getpid(), SIGTERM); //it ends the process when the threads finish.
}
}
这是输出的片段:
New Thread [1] created in Component [Velocity] with id 140236340983552
New Thread [1] created in Component [FaceRecognition] with id 140236340983552
New Thread [1] created in Component [Trajectories] with id 140236340983552
New Thread [2] created in Component [Velocity] with id 140236332590848
New Thread [2] created in Component [Trajectories] with id 140236332590848
New Thread [2] created in Component [FaceRecognition] with id 140236332590848
来自不同进程的线程可以有相同的id吗?奇怪,每个线程的标识符应该是唯一的吧?
【问题讨论】:
-
当然他们可以在不同的进程中拥有相同的 id,你为什么认为他们不能呢? “奇怪,每个线程的标识符应该是唯一的吧?”不,这个假设是错误的,你从哪里得到的?
-
在单个进程内存空间中是唯一的,我不明白为什么您可以在其他情况下确定这种唯一性。
-
不同程序如何知道彼此创建的线程的 ID,它们需要这些 ID 才能保持唯一性?
-
我知道每个进程都在内存中保留了它的空间,并且一个进程的线程共享该空间。但令我特别震惊的是,每个进程的第一个线程具有相同的标识符。对于那些以二阶和三阶创造的人来说也是如此。也许这可能发生在来自同一个父亲的进程中。
标签: c++ multithreading process