#include <thread>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <functional>
using namespace std;
mutex print_mutex;
condition_variable cond;
string s = "";
int flag = 0;
bool pred(int num){
if (flag >= s.size() || s[flag]-'0'==num)
return true;
else return false;
}
void thread_fun(int num){
while (flag < s.size()){
unique_lock<mutex> lock(print_mutex);
cond.wait(lock,bind(pred,num));
if (flag < s.size()){
cout<<num<<" from"<<this_thread::get_id()<<endl;
flag++;
cond.notify_all();
}
}
//cout<<"JIESHULOP"<<" from"<<this_thread::get_id()<<endl;
//cond.notify_all();
}
int main(int argc, char const *argv[])
{
vector<thread> threads;
cin>>s;
for (int i=0;i<10;i++)
threads.push_back(thread(thread_fun,i));
for (int i=0;i<10;i++)
threads[i].join();
cout<<"end"<<endl;
return 0;
}
运行结果
111122256635645
1 from3
1 from3
1 from3
1 from3
2 from4
2 from4
2 from4
5 from7
6 from8
6 from8
3 from5
5 from7
6 from8
4 from6
5 from7
end