Sleep (n) is used to sleep the current thread for N milliseconds to execute other threads. If there are no other threads, the thread will continue to run after N milliseconds of sleep.
If n = 0, sleep (0) means that the CPU hands over the execution right of the current thread and allows the CPU to execute other threads. That is, discard the time slice of the current thread and execute other threads.
So, in which case should sleep (0) be used? Generally, if the current thread consumes a lot of CPU resources, you can add sleep (0) At the end, which greatly improves the efficiency.
In addition, this method can be used to ensure thread synchronization. When the thread pool is working, the main thread uses sleep (0) to wait for all threads in the thread pool to complete the operation. When there are many threads in the thread pool, this method is indeed a very effective way to save CPU, because it saves the overhead of using the kernel for synchronization in the thread.
-
- VoidSetcopyfile (ShortProgress)
-
- {
- If(Progress! = 100 & m_t1)
-
- M_t1 = false;
-
- If(M_copypro + m_span <= progress | 100 = progress)
-
- {
-
- If(100 = Progress & m_t1)
-
- Return;
- : Postmessage (m_pchiddenwnd-> m_hwnd, wm_ccopyprogress, progress, 0 );
-
- M_copypro = progress;
-
- Sleep (0 );
-
- }
-
- }
AboveCodeBecause the code is in a multi-threaded running environment, and the copy progress SS is continuously carried out, the postmessage () function is constantly called, message ing is also required, and the corresponding message function is executed, therefore, this is a time-consuming process. At this time, sleep (0) comes in handy,Add it to the backend so that other threads can be run in a timely manner.
Sleep (0)
Previously, in the same process, sleep (0) was especially preferred for Thread Synchronization in some cases. For example, when the thread pool works, the main thread uses sleep (0) to wait for all threads in the thread pool
Complete the operation. When there are many threads in the thread pool, this method is indeed a very effective way to save CPU, because it saves the overhead of using the kernel for synchronization in the thread. And it is very important.
It works well and can be said to be completely under my control.
However, after I change to a dual-core CPU, the problem arises: Sleep (0) is often returned earlier than expected. The original design code did not consider Thread Scheduling in multi-core/multi-CPU mode.
It seems that the speed and convenience are still difficult to get the best of both worlds. If the data is sensitive to synchronization, you still cannot cut corners.
In addition, the test found a strange point: when the thread pool is working, when the task manager sets that the process can only run on one CPU, the amount of memory occupied by the city continues to grow rapidly. When the configuration is enabled for scheduling under dual-core, the amount of memory starts to decrease slowly.