?
鴻蒙系統的多線程編程步驟:
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);