Question of threads

I have two threads,I want to thread2 running only when thread1 is idle,so I set the priority of thread1 to 41 and the priority of thread2 to 40,I make a test that set a special delay time to thread1 to simulate its exection time,when the time is more than 50ms,it’s ok,but when the delay time is less than 50ms,sometimes thread2 has no chance to run,in my project the delay time of thread1 is only 2ms,how do I deal with the problem?

well, how are you testing to see if thread2 is running?

I use printf() to see if thread2 is running

Well, printf() does a lot of stuff. Not only formating/etc in libc, but also causes messages to be sent to the server managing your stdout/stderr file descriptors. Since server’s float to the priority of the client (normally), that server will also fall to a lower priority then your thread1.

Also - generally using priorities between threads to force syncronization like this is not a good thing. It doesn’t work on SMP and can lead to odd behaviors. A better thing to do is have a mutex or semaphore and have thread2 wait until thread1 says it can run and only run as long as that condition is true.

I also want to use mutex,in my project, thread1 is resposible for getting data from dsp,thread2 is resposible for saving a large data to the file in emergency,thread2 is a contionus thread,its running should not effect running of thread1,if I use mutex,I have to use several times in thread2,but how to control the occation?what’s your opinon? thank you!

In this case I would make an intelligent data structure using a reader/writer pattern that favors the writer. This means that thead1 will always be able to write data into the structure and that thread2 will be able to block on the structure until there is some amount X of data present. Look around online or in any textbooks on conncurent programming for explainations of reader/writer patterns.