嗨,我想同时启动我的两个for循环,原因是当我启动程序时,循环是按顺序执行的,问题是执行我的任务时,所有线程必须同时执行,每个线程与每个线程通信其他。
这是我的主音
int main(int argc, char* argv[])
{
max_jobs = std::atoi(argv[3]);
int size = std::atoi(argv[1]);
int size1 = std::atoi(argv[2]);
std::vector<std::thread> prods(size);
std::vector<std::thread> consos(size1);
for (int i=1;i<=size;i++){
prods[i] =
std::thread(producer,max_jobs);}
for (int j =1 ; j<=size1;j++){
consos[j] = std::thread(consumer);}
for (int i=1;i<=size;i++){
prods[i].join();}
for (int j =1 ; j<=size1;j++){
consos[j].join();}
return 0;
}
这是我的生产者和消费者职能部门
void producer(int max){
for (int i = 0; i<= max ; i++){
std::cout << max;
std::unique_lock<mutex> lock(m);
std::cout << "production "<< i << endl;
produced_nums.push(i);
notified = true;
cond_var.notify_one();
}
done = true;
cond_var.notify_one();
std::cout << "\n nombre de thread dans la
pile est " << produced_nums.size() << endl;
}
void consumer(){
std::unique_lock<mutex> lock(m);
while(!done){
while(!notified){
cond_var.wait(lock);
}
while(!produced_nums.empty()){
cout << "consuming " << produced_nums.top() << endl;
produced_nums.pop();
}
notified = false;
}
std::cout << "\n nombre de thread dans la
pile est " << produced_nums.size() << endl;
}