arkts线程间通信sendData,onReceiveData

150 阅读1分钟

taskpool介绍

为什么要进行线程间通信

  1. 多个线程并发执行时, 在默认情况下CPU是随机切换线程的,当我们需要多个线程来共同完成一件任务,

   并且我们希望他们有规律的执行, 那么多线程之间需要一些协调通信,以此来帮我们达到多线程共同操作一份数据

2.当然如果我们没有使用线程通信来使用多线程共同操作同一份数据的话,虽然可以实现,

  但是在很大程度会造成多线程之间对同一共享变量的争夺,那样的话势必为造成很多错误和损失!

3.所以,我们才引出了线程之间的通信,多线程之间的通信能够避免对同一共享变量的争夺。

测试用例

image.png

@Concurrent
function ConcurrentFunc(num: number): number {
  let res: number = num * 10;
  taskpool.Task.sendData(res);
  return num;
}

function pringLog(data: number): void {
  console.info("taskpool: data is: " + data);
}

export async function testFunc(): Promise<void> {
  try {
    let task: taskpool.Task = new taskpool.Task(ConcurrentFunc, 1);
    task.onReceiveData(pringLog);
    await taskpool.execute(task);
  } catch (e) {
    console.error(`taskpool: error code: ${e.code}, info: ${e.message}`);
  }
}

Index.ets中进行测试

image.png

测试成功

image.png