t2 got a value from t1:10 function_2... function_2... t2 got a value from t1:9 function_2... t2 got a value from t1:8 function_2... t2 got a value from t1:7 function_2... t2 got a value from t1:6 function_2... function_2... t2 got a value from t1:5 function_2... t2 got a value from t1:4 function_2... t2 got a value from t1:3 function_2... t2 got a value from t1:2 function_2... t2 got a value from t1:1 function_2... 请按任意键继续. . .
voidfunction_1() { int count = 10; while (count > 0) { unique_lock<mutex> locker1(mu);//使用unique_lock来管理锁 q.push_front(count);//队列中写数据(队前插入)10 9 8...1 0 locker1.unlock();//提前解锁 //cond.notify_one();//激活一个等待这个条件的线程 cond.notify_all();//激活所有类似线程2的等待线程 this_thread::sleep_for(chrono::seconds(1));//此线程休息1秒 count--; } } voidfunction_2() { int data = 0; while (data != 1) { unique_lock<mutex> locker2(mu);//互斥对象mu被线程2锁住,线程不会在锁住的情况下休眠 cond.wait(locker2, []() {return !q.empty(); });//将线程2休眠直到线程1的notify_one()才将其激活 //上句第一个参数是解锁加锁,第2个参数为【lambda函数】,防止伪激活 data = q.back();//队列中读数据 q.pop_back();//队列中删除数据(队尾删除) locker2.unlock();//提前解锁 cout << "t2 got a value from t1:" << data << endl; } }
运行结果:
1 2 3 4 5 6 7 8 9 10 11
t2 got a value from t1:10 t2 got a value from t1:9 t2 got a value from t1:8 t2 got a value from t1:7 t2 got a value from t1:6 t2 got a value from t1:5 t2 got a value from t1:4 t2 got a value from t1:3 t2 got a value from t1:2 t2 got a value from t1:1 请按任意键继续. . .
intfactorial(future<int>&f)//阶乘函数 { int res = 1; int N = f.get(); for (int i = N; i > 1; i--) res *= i; cout << "Result is:" << res << endl; return res; }
intmain()//主线程 { int x; promise<int> p;//主线程中的int变量(“约定型”变量) future<int> f = p.get_future();//该变量值的值约定从“将来”future获得 cout << "pass the promise-future 'p' to factorial()..." << endl; future<int> fu = async(launch::async, factorial, ref(f));//按引用传递f(一个未来的约定)