QtConcurrent


The namespace provides high-level APIs that make it possible to write multi-threaded programs without using low-level threading primitives.

QtConcurrent名称空间提供了高级api,可以在不使用低级线程原语的情况下编写多线程程序  

1、QtConcurrent::ReduceOptions enum provides a way to control the order in which the reduction is done. If QtConcurrent::UnorderedReduce is used (the default), the order is undefined, while QtConcurrent::OrderedReduce ensures that the reduction is done in the order of the original sequence.resultCount() function returns the number of continuous results. This means that it is always safe to iterate through the results from 0 to resultCount().

QFuture允许线程对一个或多个结果进行同步,这些结果将在稍后的时间点准备好。结果可以是具有默认构造函数和复制构造函数的任何类型。如果一个结果在调用result()、resultAt()或results()函数时不可用,QFuture将等待直到结果可用。可以使用isResultReadyAt()函数来确定一个结果是否准备好了。对于报告多个结果的QFuture对象,resultCount()函数返回连续结果的数量。这意味着迭代从0到resultCount()的结果总是安全的。

provides a ) and an ). Using these iterators is another way to access results in the future.

QFuture提供了一个java风格的迭代器(qfutuator)和一个stl风格的迭代器(QFuture::const_iterator)。使用这些迭代器是将来访问结果的另一种方式。

also offers ways to interact with a runnning computation. For instance, the computation can be canceled with the cancel() function. To pause the computation, use the setPaused() function or one of the pause(), resume(), or togglePaused() convenience functions. Be aware that not all asynchronous computations can be canceled or paused. For example, the future returned by QtConcurrent::run() cannot be canceled; but the future returned by QtConcurrent::mappedReduced() can.

QFuture还提供了与正在运行的计算交互的方法。例如,可以使用cancel()函数取消计算。要暂停计算,请使用setPaused()函数或pause()、resume()或togglePaused()方便函数之一。请注意,并不是所有的异步计算都可以取消或暂停。例如,QtConcurrent::run()返回的future不能被取消;但是由QtConcurrent::mappedReduced()返回的future可以。

Progress information is provided by the progressValue(), progressMinimum(), progressMaximum(), and progressText() functions. The waitForFinished() function causes the calling thread to block and wait for the computation to finish, ensuring that all results are available.

进度信息由progressValue()、progressMinimum()、progressMaximum()和progressText()函数提供。waitForFinished()函数导致调用线程阻塞并等待计算完成,以确保所有结果都可用。

The state of the computation represented by a can be queried using the isCanceled(), isStarted(), isFinished(), isRunning(), or isPaused() functions.

QFuture表示的计算状态可以使用isCanceled()、isStarted()、isFinished()、isRunning()或isPaused()函数来查询。

is a lightweight reference counted class that can be passed by value.

QFuture是一个轻量级引用计数类,可以按值传递。

is specialized to not contain any of the result fetching functions. Any can be assigned or copied into a as well. This is useful if only status or progress information is needed - not the actual result data.

专门化为不包含任何结果获取函数。任何 可以被赋值或复制到如果只需要状态或进度信息(而不是实际的结果数据),这是很有用的。

To interact with running tasks using signals and slots, use .

future() function returns the future set with setFuture().

QFutureWatcher提供关于QFuture的信息和通知。 使用setFuture()函数开始监视特定的QFuture。 函数的作用是:通过setFuture()返回未来集合。  

For convenience, several of 's functions are also available in : .

为了方便起见,QFuture的几个函数也可以在QFutureWatcher中使用:progressValue(), progressMinimum(), progressMaximum(), progressText(), isStarted(), isFinished(), isRunning(), isCanceled(), isPaused(), waitForFinished(), result(),和resultAt()。 cancel()、setPaused()、pause()、resume()和togglePaused()函数都是QFutureWatcher中的槽。  

Status changes are reported via the started(), finished(), canceled(), paused(), resumed(), resultReadyAt(), and resultsReadyAt() signals. Progress information is provided from the progressRangeChanged(), void progressValueChanged(), and progressTextChanged() signals.

状态变化通过started()、finished()、canceled()、paused()、resumed()、resultReadyAt()和resultsReadyAt()信号来报告。 进度信息由progressRangeChanged()、void progressValueChanged()和progressTextChanged()信号提供。  

Throttling control is provided by the setPendingResultsLimit() function. When the number of pending resultReadyAt() or resultsReadyAt() signals exceeds the limit, the computation represented by the future will be throttled automatically. The computation will resume once the number of pending signals drops below the limit.

调节控制是由setPendingResultsLimit()函数提供的。 当等待的resultReadyAt()或resultsReadyAt()信号的数量超过限制时,由future表示的计算将被自动控制。 一旦待处理信号的数量低于限制,计算将继续进行。  

Example: Starting a computation and getting a slot callback when it's finished:

示例:开始计算并在计算完成后获得一个槽回调:  

  // Instantiate the objects and connect to the finished signal.
  MyClass myObject;
  QFutureWatcher<int> watcher;
  connect(&watcher, SIGNAL(finished()), &myObject, SLOT(handleFinished()));

  // Start the computation.
  QFuture<int> future = QtConcurrent::run(...);
  watcher.setFuture(future);

Cancels the asynchronous computation represented by the future(). Note that the cancelation is asynchronous. Use waitForFinished() after calling cancel() when you need synchronous cancelation.

取消future()表示的异步计算。 注意,取消是异步的。 当你需要同步取消时,在调用cancel()之后使用waitForFinished()。  

Currently available results may still be accessed on a canceled , but new results will not become available after calling this function. Also, this will not deliver progress and result ready signals once canceled. This includes the progressValueChanged(), progressRangeChanged(), progressTextChanged(), resultReadyAt(), and resultsReadyAt() signals.

当前可用的结果仍然可以在取消的QFuture上访问,但是在调用这个函数后,新的结果将不可用。 此外,一旦取消,这个QFutureWatcher将不会交付进度和结果就绪信号。 这包括progressValueChanged(), progressRangeChanged(), progressTextChanged(), resultReadyAt()和resultsReadyAt()信号。  

Be aware that not all asynchronous computations can be canceled or paused. For example, the future returned by QtConcurrent::run() cannot be canceled; but the future returned by QtConcurrent::mappedReduced() can.

请注意,并不是所有的异步计算都可以取消或暂停。 例如,QtConcurrent::run()返回的future不能被取消; 但是由QtConcurrent::mappedReduced()返回的future可以。  

is specialized to not contain any of the result fetching functions. Any can be watched by a as well. This is useful if only status or progress information is needed; not the actual result data.

QFutureWatcher被专门用于不包含任何结果抓取函数。 任何QFuture也可以被QFutureWatcher监视。 如果只需要状态或进度信息,这很有用; 不是实际的结果数据。  

waitForFinished(), providing an easy way to ensure that all futures have finished before returning from a function:

waitForFinished()函数等待所有的期货交易完成。QFutureSynchronizer的析构函数调用waitForFinished(),提供了一种简单的方法来确保所有的期货在从函数返回之前已经完成:

  void someFunction()
  {
      QFutureSynchronizer<void> synchronizer;

      ...

      synchronizer.addFuture(QtConcurrent::run(anotherFunction));
      synchronizer.addFuture(QtConcurrent::map(list, mapFunction));

      return; // QFutureSynchronizer waits for all futures to finish
  }

The behavior of waitForFinished() can be changed using the setCancelOnWait() function. Calling setCancelOnWait(true) will cause waitForFinished() to cancel all futures before waiting for them to finish. You can query the status of the cancel-on-wait feature using the cancelOnWait() function.

waitForFinished()的行为可以通过setCancelOnWait()函数来改变。调用setCancelOnWait(true)将导致waitForFinished()在等待它们完成之前取消所有的期货。cancelOnWait()函数用于查询等待取消特性的状态。

QByteArray::split() (a const member function) in a separate thread is done like this:

例如,在一个单独的线程中调用QByteArray::split() (const成员函数)是这样的:

  // call 'QList  QByteArray::split(char sep) const' in a separate thread
  QByteArray bytearray = "hello world";
  QFuture > future = QtConcurrent::run(bytearray, &QByteArray::split, ',');
  ...
  QList result = future.result();

Calling a non-const member function is done like this:

调用非const成员函数是这样的:

  // call 'void QImage::invertPixels(InvertMode mode)' in a separate thread
  QImage image = ...;
  QFuture<void> future = QtConcurrent::run(&image, &QImage::invertPixels, QImage::InvertRgba);
  ...
  future.waitForFinished();
  // At this point, the pixels in 'image' have been inverted

Using Lambda Functions

Calling a lambda function is done like this:

调用lambda函数是这样的:

  QFuture<void> future = QtConcurrent::run([=]() {
      // Code in this block will run in another thread
  });
  ...

6、QtConcurrent::ReduceOptions enum provides a way to control the order in which the reduction is done.QString::contains():

例如,我们使用QString::contains():

bool QString::contains(const QRegularExpression ®exp) const;

QString::contains() takes 2 arguments (including the "this" pointer) and can't be used with QtConcurrent::filtered() directly, because QtConcurrent::filtered() expects a function that takes one argument. To use QString::contains() with QtConcurrent::filtered() we have to provide a value for the regexp argument:

QString::contains()接受2个参数(包括"this"指针),不能直接与QtConcurrent::filtered()一起使用,因为QtConcurrent::filtered()需要一个接受一个参数的函数。要使用QString::contains()和QtConcurrent::filtered(),我们必须为regexp参数提供一个值:

  QStringList strings = ...;
  QFuture future = QtConcurrent::filtered(list, [](const QString &str) {
      return str.contains(QRegularExpression("^\\S+$")); // matches strings without whitespace
  })

QT