在线文档教程
C++
线程支持 | Thread support

std::promise::set_value

STD::承诺::设定[医]价值

void set_value( const R& value (1)(member only of generic promise template)(since C++11)
void set_value( R&& value (2)(member only of generic promise template)(since C++11)
void set_value( R& value (3)(member only of promise<R&> template specialization)(since C++11)
void set_value((4)(member only of promise<void> template specialization)(since C++11)

原子存储value进入共享状态并使状态就绪。

这个操作的行为就像set_value,,,set_exception,,,set_value_at_thread_exit,和set_exception_at_thread_exit在更新允诺对象时获取与承诺对象关联的单个互斥对象。

如果没有共享状态,或者共享状态已经存储了值或异常,则引发异常。

参数

value-value to store in the shared state

返回值

%280%29

例外

std::future_error在下列条件下:

  • *this没有共享状态。错误类别设置为no_state...

  • 共享状态已存储值或异常。错误类别设置为promise_already_satisfied...

此外:

的副本构造函数引发的任何异常。value

2%29移动构造函数引发的任何异常。value

这个例子显示了如何promise<void>可用作线程之间的信号。

二次

#include <thread> #include <future> #include <cctype> #include <vector> #include <algorithm> #include <iterator> #include <iostream> #include <sstream> int main() { std::istringstream iss_numbers{"3 4 1 42 23 -23 93 2 -289 93"}; std::istringstream iss_letters{" a 23 b,e a2 k k?a;si,ksa c"}; std::vector<int> numbers; std::vector<char> letters; std::promise<void> numbers_promise, letters_promise; auto numbers_ready = numbers_promise.get_future( auto letter_ready = letters_promise.get_future( std::thread value_reader([&] { // I/O operations. std::copy(std::istream_iterator<int>{iss_numbers}, std::istream_iterator<int>{}, std::back_inserter(numbers) //Notify for numbers. numbers_promise.set_value( std::copy_if(std::istreambuf_iterator<char>{iss_letters}, std::istreambuf_iterator<char>{}, std::back_inserter(letters), ::isalpha //Notify for letters. letters_promise.set_value( } numbers_ready.wait( std::sort(numbers.begin(), numbers.end() if (letter_ready.wait_for(std::chrono::seconds(1)) == std::future_status::timeout) { //output the numbers while letters are being obtained. for (int num : numbers) std::cout << num << ' '; numbers.clear( //Numbers were already printed. } letter_ready.wait( std::sort(letters.begin(), letters.end() //If numbers were already printed, it does nothing. for (int num : numbers) std::cout << num << ' '; std::cout << '\n'; for (char let : letters) std::cout << let << ' '; std::cout << '\n'; value_reader.join( }

二次

产出:

二次

-289 -23 1 2 3 4 23 42 93 93 a a a a b c e i k k k s s

二次

另见

set_exceptionsets the result to indicate an exception (public member function)

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/线程/诺言/SET[医]价值