Sample Code

The multithreading, multistreaming scenario is described in Stream Management.

Principles

Allocate runtime resources including the device, context, and stream in sequence. Destroy the runtime allocations including the stream, context, and device in sequence when they are no longer needed.

Sample Code

You can view the complete code in Sample Overview.

Following the API calls, add exception handling branches and specify log printing of error and information levels. The following is a code snippet of key steps only, which is not ready to be built or run.

// Initialize variables.
extern bool g_isDevice;

// =====Runtime resource allocation=====
// Specify the compute device.
aclError ret = aclrtSetDevice(deviceId_);

// Explicitly create a context to manage the stream object.
ret = aclrtCreateContext(&context_, deviceId_);

// Explicitly create a stream.
// To reserve the execution order of asynchronous tasks.
ret = aclrtCreateStream(&stream_);

// Obtain the current run mode of the Ascend AI Software Stack. The subsequent API calls vary according to the run mode.
aclrtRunMode runMode;
ret = aclrtGetRunMode(&runMode);
g_isDevice = (runMode == ACL_DEVICE);
// =====Runtime resource allocation=====

// ......

// =====Runtime resource deallocation=====
ret = aclrtDestroyStream(stream_);
ret = aclrtDestroyContext(context_);
ret = aclrtResetDevice(deviceId_);
// =====Runtime resource deallocation=====

// ......