鸿蒙系统的多线程编程步骤:
1. 描述要创建的线程的属性配置. attr: attributeosThreadAttr_t attr;//声明一个线程属性变量memset(&attr, 0, sizeof(attr));//memset改变一个内存单元上存的值为0//以下三个为必须设置的线程属性attr.name = "ledThread"; //设置线程名称attr.stack_size = 1024; //设置栈大小。 栈就是程序执行时用于给局部变量分配空间的内存区域attr.priority = osPriorityAboveNormal;//线程优先级别2. 定义线程要执行的函数void threadLed(void *arg) {...}3. 创建线程,指定线程要执行的函数,执行函数时传递的参数,线程属性成功创建会得到一个线程IDosThreadId_t threadID = osThreadNew(threadLed, NULL, &attr); 4. 通过线程ID可回收线程资源,结束线程执行osThreadTerminate(threadID); // 结束线程执行osThreadJoin(threadID); // 回收线程资源
实践:创建3个线程,每个线程循环定时控制一个IO口的高低电平状态:
#include <stdio.h>
#include <ohos_init.h>
#include <hi_io.h>
#include <iot_gpio.h>
#include <iot_errno.h>
#include <unistd.h>
#include <cmsis_os2.h>#define LED_IO HI_IO_NAME_GPIO_2
#define LED_FUNC HI_IO_FUNC_GPIO_2_GPIO#define BUZZER_IO HI_IO_NAME_GPIO_5
#define BUZZER_FUNC HI_IO_FUNC_GPIO_5_GPIOstruct MyThreadArg {char *threadName;//线程名 int io;//IO口int ioFunc;//IO口功能int interval;//延时时间us
};struct MyThreadArg threadArgs[] = {{"ledThread", LED_IO, LED_FUNC, 1000000},{"buzzerThread", BUZZER_IO, BUZZER_FUNC, 2000},{"buzzer2Thread", HI_IO_NAME_GPIO_11, HI_IO_FUNC_GPIO_11_GPIO, 2000},
};void threadFunc(void *arg)
{struct MyThreadArg *threadArg = (struct MyThreadArg *)arg;if (IOT_SUCCESS != IoTGpioInit(threadArg->io)){printf("led io init failed\n");return;}hi_io_set_func(threadArg->io, threadArg->ioFunc);IoTGpioSetDir(threadArg->io, IOT_GPIO_DIR_OUT);while (1){IoTGpioSetOutputVal(threadArg->io, 1);usleep(threadArg->interval);IoTGpioSetOutputVal(threadArg->io, 0);usleep(threadArg->interval); }
}void createMyThread(struct MyThreadArg *threadArg)
{osThreadAttr_t attr;//声明一个线程属性变量memset(&attr, 0, sizeof(attr));//memset改变一个内存单元上存的值attr.name = threadArg->threadName;attr.stack_size = 1024; //设置栈大小。 栈就是程序执行时用于给局部变量分配空间的内存区域attr.priority = osPriorityAboveNormal;//线程优先级别osThreadId_t threadID = osThreadNew(threadFunc, threadArg, &attr);
}void myhello_test()
{int i;printf("myhello test\n");for (i = 0; i < hi_array_size(threadArgs); i++)createMyThread(&threadArgs[i]);
}SYS_RUN(myhello_test);