大家看我前一主题帖上面的图了吧
输出大概是这个样子,但是为什么会有乱码呢?难道是实时操作系统线程出问题了吗?! ^ T7 ^4 f/ [. }# \$ t; x 这里就要说一下显示乱码的原因了 之所以需要线程同步是因为在多线程并行执行的情况下,有可能会造成多线程同时使用同一系统资源的情况,从而造成冲突的发生,影响程序执行的正确性,在操作系统中一般使用互斥锁与信号量来实现线程同步 只有拥有互斥对象的线程才有访问公共资源的权限,因为互斥对象只有一个,所以能保证公共资源不会同时被多个线程访问。互斥不仅能实现同一应用程序的公共资源安全共享,还能实现不同应用程序的公共资源安全共享! M! ^6 [3 u! `6 K; s" ?9 ?0 | 信号量:它允许多个线程在同一时刻访问同一资源,但是需要限制在同一时刻访问此资源的最大线程数目! x M! J' g! e' x; F. G. A 所以,我们可以给线程在调用时加个判断,判断的内容就是线程里面的信号量或者是互斥量。6 n. ~- G. l% I/ e( G4 ?8 p0 P #include "rtos.h" #include "mbed.h" Serial pc(USBTX,USBRX);. D8 M% A- S5 x/ H6 d Mutex stdio_mutex; // Semaphore slots(1);' S& D0 R. [" W& q ; m* o: W- e) g- @ uint8_t theadindex[3];, f. f4 K7 |. u2 d$ P ) ^3 j' j0 r' Z2 Z- E4 i# n( o) a long count[3];' a5 Y L J- v% K5 E, f( c7 \ void printstr(void const *args) 3 m! y1 n4 f- E# g- P3 W; h: f {9 D) ]) e1 v: i. L4 A8 ?! v , y b' y; j" X; ], Z7 Z 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());# Q: [( A8 }6 L1 I, h. a% E7 m count[*(uint8_t *)args-1]++;3 X8 R( d: s+ [- ]' L# T0 P stdio_mutex.unlock();//slot.release(); Thread::yield(); $ r; n1 j( A: t! q J/ H6 X } }5 L+ H8 C5 | t. S; W int main() {* h& [2 X+ {# f; p2 U8 g+ ~9 G, [ theadindex[0]=1; theadindex[1]=2;& m# A, a8 D" f; D theadindex[2]=3;! ^8 @2 q2 s2 ` 9 a8 k' q- x- s6 O! G- p6 y Thread thread1(printstr,(void *)theadindex,osPriorityNormal); 4 {5 c0 ~ c5 {* P6 d Thread thread2(printstr,(void *)(theadindex+1),osPriorityNormal);0 V- `& P P5 ^9 C# V* K0 a / K( c' r6 }) q Thread thread3(printstr,(void *)(theadindex+2),osPriorityNormal); * m7 a* ~% S; Q4 h% Z2 I6 Q: `% O while (1) {/ y6 b; K5 h! s! S2 a, ^2 Q% ` / W, J4 e# f# @ stdio_mutex.lock();//slots.wait();) {* [5 y! ]9 y5 u. k/ P 4 S- W1 C+ @" _8 a F% G pc.printf("Thread1 count is %ld,Thread2 count is %ld,,Thread3 count is %ld. \n",count[0],count[1],count[2]); I( r/ G5 \4 u& O c- _. @* y stdio_mutex.unlock();//slot.release(); 1 v5 X" @- ^0 b8 y Thread::wait(1000); }: D5 R; l4 c2 g" M7 U } mbed-rtos另外还提供了一种称为Signals(信号)的精简同步模式,在这种模式下,一个线程必须等到特定的信号到来才继续,而另外一个线程则负责发送该信号 |
看来我也要学习一下了,看起来好好玩的样子 |
|
|
学习下!! |
非常好,学习了一下 |
非常感谢楼主的分想 |
帮顶,还没有用过RTOS |
我会发更加好的帖子的 |