[返回博客](/cn/blog) # 使用多线程

Vadim Asandiy 五月 26, 2023

<a class="a2a_button_facebook"></a><a class="a2a_button_twitter"></a><a class="a2a_button_linkedin"></a>

对于多线程加载和重新生成，BimNv SDK 使用 Intel® oneAPI Threading Building Blocks (oneTBB) 库。

### 多线程加载

默认情况下，线程计数从 ODA 线程池获取。但是，如果需要在多线程模式下加载文件时设置线程计数，请重写 OdDbBaseHostAppServices 中的方法 virtual int numThreads(OdDb::MultiThreadedMode mtMode)。例如：

```
//…
class MyServices : public OdNwHostAppServices
{
  //…  
  //method for setting thread count
  void setNumThreads(int numThreads)
  {
    m_numThreads = numThreads;
  }

  // override method for getting thread count
  int numThreads(OdDb::MultiThreadedMode mtMode) override
  {
    int numThrs = 1;
    bool bEnabled = false;
    switch (mtMode)
    {
      case OdDb::kMTLoading:
      bEnabled = GETBIT(getMtMode(), 1);
      break;
    }
    if (bEnabled)
      numThrs = m_numThreads;
      return numThrs;
  }

  protected:
    int m_numThreads;
};
//…
```

要在多线程模式下打开文件，请使用以下代码：

```
//…
OdNwHostAppServices* pHostApp;
OdString nwFile;
//…
OdInt16 nMode = pHostApp->getMtMode();

//set mt loading mode
SETBIT_1(nMode, 1);
pHostApp->setMtMode(nMode);
MyServices* pMyHostApp = dynamic_cast<MyServices*>(pHostApp);

//if our pHostApp contain override method for thread count's getting – then set 8 threads, for example
if (pMyHostApp != nullptr)
  pMyHostApp->setNumThreads(8);
OdNwDatabasePtr pDb = pHostApp->readFile(nwFile);
//… 
```

下表显示了与单线程模式相比，多线程加载的时间减少情况：

| | 部分加载 | 部分加载 | 部分加载 | 完全加载 | 完全加载 | 完全加载 |
| :---: | :---: | :---: | :---: | :---: | :---: | :---: |
| | st vs mt2 | st vs mt4 | st vs mt8 | st vs mt2 | st vs mt4 | st vs mt8 |
| 平均 <br> 改进 | -9% | -20% | -16% | -7% | -35% | -38% |

### 多线程再生

对于使用 Gi/Gs 矢量化的多线程再生，您可以将线程计数设置为 GS 设备属性：

```
//...
OdNwHostAppServices* pHostApp;
OdGsDevicePtr pDevice;
OdString nwFile;
OdUInt32 mtRegenThreadCnt;
//...
OdNwDatabasePtr pDb = pHostApp->readFile(nwFile);
//...
// Initialize GsDevice and set additional properties to GiContext
//...
OdRxDictionaryPtr devProperties = pDevice->properties();
devProperties->putAt(OD_T("EnableMultithread"), OdRxVariantValue(true));
devProperties->putAt(OD_T("MaxRegenThreads"), OdRxVariantValue(static_cast<OdUInt16>(mtRegenThreadCnt)));
//…
//now update of Gs device is going in mt-regen mode
pDevice->update();
//...
```

对于离屏矢量化设备，请将 GS 设备属性 ForcePartialUpdate 设置为 true：

```
//…
devProperties->putAt(OD_T("ForcePartialUpdate"), OdRxVariantValue(true));
//…
```

下表显示了与单线程模式相比，多线程再生中的时间减少情况：

| | st vs mt2 | st vs mt4 | st vs mt8 |
| :---: | :---: | :---: | :---: |
| 平均改进 | -28% | -45% | -42% |

以下硬件用于获取统计数据：

- Intel® Core™ i7-6700 CPU @ 3.40GHz; 1个插槽，4个核心，8个逻辑处理器
- 32GB 内存，速度 2133MHz
- 硬盘

在[我们的文档](https://docs.opendesign.com/bimnv/bimnv_working_with_multi-threading.html)中了解更多信息。

## 今天就开始行动

**免费试用 ODA 软件 60 天。  
无风险，无需信用卡。**

[免费试用](https://www.opendesign.com/cn/free-trial)
