QPromise Class
template <typename T> class QPromiseQPromise 클래스는 QFuture 에서 액세스할 수 있도록 계산 결과를 저장하는 방법을 제공합니다. 더 보기...
| 헤더: | #include <QPromise> |
| CMake: | find_package(Qt6 REQUIRED COMPONENTS Core) target_link_libraries(mytarget PRIVATE Qt6::Core) |
| qmake: | QT += core |
| 다음부터: | Qt 6.0부터 |
- 상속된 멤버를 포함한 모든 멤버 목록
- QPromise는 스레딩 클래스의 일부입니다.
참고: 이 클래스의 모든 함수는 스레드 안전합니다.
공개 함수
| QPromise() | |
| QPromise(const QPromise<T> &) | |
| QPromise(QPromise<T> &&other) | |
| ~QPromise() | |
| bool | addResult(T &&result, int index = -1) |
| bool | addResult(const T &result, int index = -1) |
(since 6.6) bool | addResults(const QList<T> &results) |
(since 6.6) bool | emplaceResult(Args &&... args) |
(since 6.6) bool | emplaceResultAt(int index, Args &&... args) |
| void | finish() |
| QFuture<T> | future() const |
| bool | isCanceled() const |
| void | setException(const QException &e) |
| void | setException(std::__exception_ptr::exception_ptr e) |
| void | setProgressRange(int minimum, int maximum) |
| void | setProgressValue(int progressValue) |
| void | setProgressValueAndText(int progressValue, const QString &progressText) |
| void | start() |
| void | suspendIfRequested() |
| void | swap(QPromise<T> &other) |
| QPromise<T> & | operator=(QPromise<T> &&other) |
| QPromise<T> & | operator=(const QPromise<T> &) |
상세 설명
QPromise는 템플릿 매개변수 T 가 저장할 수 있는 결과 유형을 지정하고, 나중에 QFuture 를 통해 해당 결과에 액세스할 수 있는 템플릿 클래스입니다.
QPromise는 사용자 정의 계산의 진행 상황과 결과를 QFuture 에 비동기 방식으로 전달하는 간단한 방법을 제공합니다. 통신이 제대로 작동하려면 QFuture 가 QPromise에 의해 생성되어야 합니다.
세밀한 제어가 필요한 경우 QPromise 기반 워크로드를 Qt ConcurrentQFuture 와 함께 사용할 수 있는 고수준 통신 기본 요소만으로도 충분할 때, QPromise 기반 워크로드를 대안으로 사용할 수 있습니다.
프로미스와 퓨처의 협업 중 가장 간단한 경우는 단일 결과 통신일 것입니다:
QPromise<int> promise;
QFuture<int> future = promise.future();
const std::unique_ptr<QThread> thread(QThread::create([] (QPromise<int> promise) {
promise.start(); // notifies QFuture that the computation is started
promise.addResult(42);
promise.finish(); // notifies QFuture that the computation is finished
}, std::move(promise)));
thread->start();
future.waitForFinished(); // blocks until QPromise::finish is called
future.result(); // returns 42설계상 QPromise는 이동 전용(move-only) 객체입니다. 이 동작은 프로미스가 소멸될 때마다 관련 퓨처 객체가 알림을 받아 결과가 준비될 때까지 무한정 대기하지 않도록 보장하는 데 도움이 됩니다. 그러나 서로 다른 스레드에서 결과를 보고하기 위해 동일한 프로미스를 사용하려는 경우에는 이 점이 불편할 수 있습니다. 현재 이를 위한 구체적인 방법은 없지만, 스마트 포인터나 원시 포인터/참조 등을 사용하는 것과 같은 알려진 메커니즘이 존재합니다. 프로미스를 복사하여 여러 곳에서 동시에 사용하고자 한다면 ` QSharedPointer `가 좋은 기본 선택지입니다. 원시 포인터나 참조는 어떤 의미에서는 더 간단하고, 아마도 성능도 더 우수할 수 있습니다(리소스 관리가 필요 없기 때문). 하지만 '덩글링(dangling)' 현상이 발생할 수 있습니다.
다음은 여러 스레드에서 Promise를 사용하는 방법의 예시입니다:
const auto sharedPromise = std::make_shared<QPromise<int>>();
QFuture<int> future = sharedPromise->future();
// ...
sharedPromise->start();
// here, QPromise is shared between threads via a smart pointer
const std::unique_ptr<QThread> threads[] = {
std::unique_ptr<QThread>(QThread::create([] (auto sharedPromise) {
sharedPromise->addResult(0, 0); // adds value 0 by index 0
}, sharedPromise)),
std::unique_ptr<QThread>(QThread::create([] (auto sharedPromise) {
sharedPromise->addResult(-1, 1); // adds value -1 by index 1
}, sharedPromise)),
std::unique_ptr<QThread>(QThread::create([] (auto sharedPromise) {
sharedPromise->addResult(-2, 2); // adds value -2 by index 2
}, sharedPromise)),
// ...
};
// start all threads
for (auto& t : threads)
t->start();
// ...
future.resultAt(0); // waits until result at index 0 becomes available. returns value 0
future.resultAt(1); // waits until result at index 1 becomes available. returns value -1
future.resultAt(2); // waits until result at index 2 becomes available. returns value -2
sharedPromise->finish();QFuture도 참조하십시오 .
멤버 함수 문서
[default] QPromise::QPromise()
기본 상태를 가진 QPromise를 생성합니다.
[delete] QPromise::QPromise(const QPromise<T> &)
QPromise 의 인스턴스를 복사 생성합니다. 이 함수는 삭제되었습니다.
[default] QPromise::QPromise(QPromise<T> &&other)
Move는 other 에서 새로운 QPromise를 생성합니다.
operator=()도 참조하십시오 .
QPromise::~QPromise()
프로미스를 파기합니다.
참고: 사용자가 사전에 ` finish()`를 호출하지 않는 한,프로미스는 소멸 시 암묵적으로 취소된 상태로 전환됩니다.
bool QPromise::addResult(T &&result, int index = -1)
bool QPromise::addResult(const T &result, int index = -1)
다음과 동일합니다
emplaceResultAt(index, result); // first overload
emplaceResultAt(index, std::move(result)); // second overload또는, index == -1 (기본값)인 경우
emplaceResult(result); // first overload
emplaceResult(std::move(result)); // second overloademplaceResultAt(), emplaceResult(), addResults()도 참조하십시오 .
[since 6.6] bool QPromise::addResults(const QList<T> &results)
내부 결과 컬렉션의 끝에 ` results `를 추가합니다.
results 가 컬렉션에 추가되면 true 를 반환합니다.
이 프로미스가 취소(canceled) 또는 완료(finished) 상태일 때 false 를 반환합니다.
results이는 addResult()을 반복 처리하는 것보다 더 효율적입니다. 개별 addResult() 호출의 경우와 달리, addResults() 호출 한 번당 관련 퓨처에 한 번만 알림이 전송되기 때문입니다. 하지만 각 요소의 계산에 시간이 걸리는 경우, 수신 측(퓨처)의 코드는 모든 결과가 보고될 때까지 진행할 수 없으므로, 연속된 요소들의 계산이 비교적 빠른 경우에만 이 함수를 사용하십시오.
이 함수는 Qt 6.6에서 도입되었습니다.
addResult()도 참조하십시오 .
[since 6.6] template <typename... Args, std::enable_if_t<std::is_constructible_v<T, Args...>, bool> = true> bool QPromise::emplaceResult(Args &&... args)
[since 6.6] template <typename... Args, std::enable_if_t<std::is_constructible_v<T, Args...>, bool> = true> bool QPromise::emplaceResultAt(int index, Args &&... args)
args... 로 구성된 결과를 내부 결과 컬렉션의 index 위치(emplaceResultAt()) 또는 컬렉션의 끝(emplaceResult())에 추가합니다.
결과가 컬렉션에 추가되면 true 를 반환합니다.
이 프로미스가 취소되거나 완료된 상태이거나 결과가 거부된 경우 false 를 반환합니다. addResult()는 컬렉션에 동일한 인덱스에 이미 다른 결과가 저장되어 있는 경우 결과 추가를 거부합니다.
이 함수들은 T 가 다음에서 생성될 수 있는 경우에만 오버로드 해결에 참여합니다. args....
QFuture::resultAt()을 호출하여 특정 인덱스의 결과를 가져올 수 있습니다.
참고: 임의의 인덱스를 지정하여 해당 인덱스의 결과를 요청할 수있습니다 . 그러나 일부 QFuture 메서드는 연속적인 결과를 처리합니다. 예를 들어, QFuture::resultCount() 또는 QFuture::const_iterator 를 사용하는 반복적 접근 방식이 있습니다. 인덱스 간격이 있는지 여부를 고려하지 않고 사용 가능한 모든 결과를 얻으려면 QFuture::results()를 사용하십시오.
이 함수들은 Qt 6.6에서 도입되었습니다.
addResult() 및 addResults()도 참조하십시오 .
void QPromise::finish()
계산이 완료되었음을 알립니다. 계산이 완료되면 addResult()을 호출해도 새로운 결과가 추가되지 않습니다. 이 메서드는 start()과 함께 사용됩니다.
QFuture::isFinished(), QFuture::waitForFinished(), start()도 참조하십시오 .
QFuture<T> QPromise::future() const
이 프롬라이즈와 연관된 퓨처를 반환합니다.
bool QPromise::isCanceled() const
QFuture::cancel() 함수를 통해 계산이 취소되었는지 여부를 반환합니다. 반환값 true 은 계산을 완료하고 finish()를 호출해야 함을 나타냅니다.
참고: 취소후에도 현재 사용 가능한 결과에는 향후에도 계속 접근할 수 있지만, addResult()를 호출할 때 새로운 결과는 추가되지 않습니다.
void QPromise::setException(const QException &e)
e 예외를 계산 결과로 설정합니다.
참고: 계산 실행 전체 과정에서 예외를 최대 하나만 설정할 수있습니다 .
참고: 이 메서드는 QFuture::cancel() 또는 finish()을 호출한 후에는 아무런 효과가 없습니다.
isCanceled()도 참조하십시오 .
void QPromise::setException(std::__exception_ptr::exception_ptr e)
이것은 오버로드된 함수입니다.
void QPromise::setProgressRange(int minimum, int maximum)
계산의 진행 범위를 minimum 과 maximum 사이로 설정합니다.
maximum 이 minimum 보다 작을 경우, minimum 이 유일한 유효한 값이 됩니다.
진행률 값은 minimum 으로 재설정됩니다.
setProgressRange(0, 0)을 사용하여 진행률 범위 기능을 비활성화할 수 있습니다. 이 경우 진행률 값도 0으로 재설정됩니다.
QFuture::progressMinimum(), QFuture::progressMaximum(), QFuture::progressValue()도 참조하십시오 .
void QPromise::setProgressValue(int progressValue)
계산의 진행률 값을 ` progressValue`로 설정합니다. 진행률 값은 증가만 가능합니다. 이 메서드는 ` setProgressValueAndText(progressValue, QString())`를 호출하기 위한 편의 메서드입니다.
progressValue 가 진행률 범위를 벗어날 경우, 이 메서드는 아무런 효과를 발휘하지 않습니다.
QFuture::progressValue() 및 setProgressRange()도 참조하십시오 .
void QPromise::setProgressValueAndText(int progressValue, const QString &progressText)
계산의 진행률 값과 진행률 텍스트를 각각 progressValue 및 progressText 로 설정합니다. 진행률 값만 증가시킬 수도 있습니다.
참고: 이 함수는 프롬이스가 취소됨(canceled) 또는 완료됨(finished) 상태인 경우 아무런 효과가 없습니다.
QFuture::progressValue(), QFuture::progressText(), QFuture::cancel(), finish()도 참조하십시오 .
void QPromise::start()
계산이 시작되었음을 보고합니다. ` QFuture ` 메서드는 이 정보에 의존하므로, 계산의 시작을 알리기 위해 이 메서드를 호출하는 것이 중요합니다.
참고: 새로 생성된 스레드에서 start()를 호출할 때는각별한 주의가 필요합니다. 이러한 경우, 스레드 스케줄링의 구현 세부 사항으로 인해 호출이 자연스럽게 지연될 수 있습니다.
관련 항목: QFuture::isStarted(), QFuture::waitForFinished(), finish().
void QPromise::suspendIfRequested()
현재 실행 스레드를 조건부로 일시 중지하고, ` QFuture`의 해당 메서드에 의해 재개되거나 취소될 때까지 대기합니다. 이 메서드는 ` QFuture::suspend()` 또는 다른 관련 메서드를 통해 계산의 일시 중지가 요청되지 않는 한 차단되지 않습니다. 실행이 일시 중지되었는지 확인하려면 ` QFuture::isSuspended()`를 사용하십시오.
참고: 여러 스레드에서 동일한 Promise를 사용하는경우 , Promise를 보유한 스레드 중 하나라도 일시 중지되면 QFuture::isSuspended()는 즉시 true 로 변경됩니다.
다음 코드 예제는 일시 중지 메커니즘의 사용법을 보여줍니다:
// Create promise and future
QPromise<int> promise;
QFuture<int> future = promise.future();
promise.start();
// Start a computation thread that supports suspension and cancellation
const std::unique_ptr<QThread> thread(QThread::create([] (QPromise<int> promise) {
for (int i = 0; i < 100; ++i) {
promise.addResult(i);
promise.suspendIfRequested(); // support suspension
if (promise.isCanceled()) // support cancellation
break;
}
promise.finish();
}, std::move(promise)));
thread->start();QFuture::suspend()는 관련된 프롬라이스를 일시 중지하도록 요청합니다:
future.suspend();QFuture::isSuspended()이 true 로 변경된 후에는 중간 결과를 가져올 수 있습니다:
future.resultCount(); // returns some number between 0 and 100
for (int i = 0; i < future.resultCount(); ++i) {
// process results available before suspension
}일시 중지된 상태에서 대기 중인 계산을 재개하거나 취소할 수 있습니다:
future.resume(); // resumes computation, this call will unblock the promise
// alternatively, call future.cancel() to stop the computation
future.waitForFinished();
future.results(); // returns all computation results - array of values from 0 to 99QFuture::resume(), QFuture::cancel(), QFuture::setSuspended(), QFuture::toggleSuspended()도 참조하십시오 .
[noexcept] void QPromise::swap(QPromise<T> &other)
이 프로미스를 ` other`로 교체합니다. 이 작업은 매우 빠르며 절대 실패하지 않습니다.
[noexcept] QPromise<T> &QPromise::operator=(QPromise<T> &&other)
Move는 ` other `를 이 프롬이스에 할당하고, 이 프롬이스에 대한 참조를 반환합니다.
[delete] QPromise<T> &QPromise::operator=(const QPromise<T> &)
other 를 이 QPromise 인스턴스에 복사-할당합니다. 이 함수는 삭제되었습니다.
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.