|
本帖最后由 ddllxxrr 于 2014-9-8 16:43 编辑
前个贴是一个线程,这里是两个线程
类名 | | | | Thread(void (*task)(void const *argument), void *argument=NULL, osPriority priority=osPriorityNormal, uint32_t stack_size=DEFAULT_STACK_SIZE, unsigned char *stack_pointer=NULL); | 构造函数,输出参数分别是任务函数指针,函数参数指针,线程优先级,堆栈大小,堆栈指针,默认为普通优先级,2K字节内存堆栈,使用内部分配方式,如果传入堆栈指针,则使用传入指针指向的内存 | | | osStatus set_priority(osPriority priority); | | osPriority get_priority(); | | int32_t signal_set(int32_t signals); | | | | static osEvent signal_wait(int32_t signals, uint32_t millisec=osWaitForever); | | static osStatus wait(uint32_t millisec); | | | | static osThreadId gettid(); | |
为了保证正常运行,除了加了优先级外还有 Thread::wait方法就不会一样了,因为它等待的时间内并不需要运行权,所以别的低优先级的线程就有了运行的机会,但一定要注意的是,任何一个子线程必须有释放运行权的机制,否则别的线程就不再有运行的机会,
以下是程序:
- #include "mbed.h"
- #include "rtos.h"
- Serial pc(USBTX,USBRX);
- uint8_t theadindex[2];
- long count[2];
- void printstr(void const *args)
- {
- while (true) {
- count[*(uint8_t *)args-1]++;
- Thread::wait(500);
- }
- }
- int main()
- {
- theadindex[0]=1;
- theadindex[1]=2;
- Thread thread1(printstr,(void *)theadindex,osPriorityNormal);
- Thread thread2(printstr,(void *)(theadindex+1),osPriorityHigh);
- while (1)
- {
- pc.printf("Thread1 count is %ld,Thread2 count is %ld. \n",count[0],count[1]);
- Thread::wait(1000);
- }
- }
-
复制代码以下是运行效果:
|
|