大家看我前一主题帖上面的图了吧
输出大概是这个样子,但是为什么会有乱码呢?难道是实时操作系统线程出问题了吗? 这里就要说一下显示乱码的原因了 之所以需要线程同步是因为在多线程并行执行的情况下,有可能会造成多线程同时使用同一系统资源的情况,从而造成冲突的发生,影响程序执行的正确性,在操作系统中一般使用互斥锁与信号量来实现线程同步 只有拥有互斥对象的线程才有访问公共资源的权限,因为互斥对象只有一个,所以能保证公共资源不会同时被多个线程访问。互斥不仅能实现同一应用程序的公共资源安全共享,还能实现不同应用程序的公共资源安全共享 信号量:它允许多个线程在同一时刻访问同一资源,但是需要限制在同一时刻访问此资源的最大线程数目 所以,我们可以给线程在调用时加个判断,判断的内容就是线程里面的信号量或者是互斥量。 #include "rtos.h" #include "mbed.h" Serial pc(USBTX,USBRX); Mutex stdio_mutex; // Semaphore slots(1); uint8_t theadindex[3]; long count[3]; void printstr(void const *args) { while (true) { stdio_mutex.lock();//slots.wait(); pc.printf("Hello World,My Thread Name is %d,Thread ID is %d.\n",*(uint8_t *)args,Thread::gettid()); count[*(uint8_t *)args-1]++; stdio_mutex.unlock();//slot.release(); Thread::yield(); } } int main() { theadindex[0]=1; theadindex[1]=2; theadindex[2]=3; Thread thread1(printstr,(void *)theadindex,osPriorityNormal); Thread thread2(printstr,(void *)(theadindex+1),osPriorityNormal); Thread thread3(printstr,(void *)(theadindex+2),osPriorityNormal); while (1) { stdio_mutex.lock();//slots.wait(); pc.printf("Thread1 count is %ld,Thread2 count is %ld,,Thread3 count is %ld. \n",count[0],count[1],count[2]); stdio_mutex.unlock();//slot.release(); Thread::wait(1000); } } mbed-rtos另外还提供了一种称为Signals(信号)的精简同步模式,在这种模式下,一个线程必须等到特定的信号到来才继续,而另外一个线程则负责发送该信号
|
| 学习,谢谢分享 |
| 看来我也要学习一下了,看起来好好玩的样子 |
|
|
| 学习下!! |
| 非常好,学习了一下 |
| 非常感谢楼主的分想 |
| 帮顶,还没有用过RTOS |
| 再顶一下 |
微信公众号
手机版