我需要在while循环内运行一个函数,作为一个单独的过程,该过程将始终在每个循环中获取新的输入。我不确定该定义的正式用语是什么。我正在考虑std::thread
,但不确定是否是使用线程的正确方法。示例:
void Foo(int i){
//..... bunches of operations
}
int main(){
int i = 0;
std::thread th1;
while(i < 5) // exit flag example
{
i++; //incremented i
th1 = std::thread(Foo,i); //run the function as separated process that takes new value of i
// .... other operations
}
th1.join(); //finish processing the thread
return 0;
}
以上程序不适用于Aborted (core dumped)
,我想我的C驱动器内存大大减少了,导致内存泄漏。
更新:如果我将join
放入循环中,程序将正常工作
while(i < 5)
{
i++; //incremented i
th1 = std::thread(Foo,i); //run the function as separated process that takes new value of i
std::cout<<"test"<<std::endl;
th1.join(); //finish processing the thread
}
但是我不确定线程和主进程是否同时运行,还是像正常函数一样运行。有人知道正确的方法吗?