对于多线程同步来说:当其中的一个线程睡眠的时候,是转而执行其他的线程还是继续等待?
看完孙鑫老师的线程死锁,本人感觉是当一个线程睡眠的时候是执行其他线程的。 不知道理解的对不对?
死锁的程序为:
#include <windows.h>
#include <iostream.h>DWORD WINAPI Fun1Proc(
  LPVOID lpParameter   // thread data
);DWORD WINAPI Fun2Proc(
  LPVOID lpParameter   // thread data
);int tickets=100;CRITICAL_SECTION g_csA;
CRITICAL_SECTION g_csB;void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2); InitializeCriticalSection(&g_csA);
InitializeCriticalSection(&g_csB);
Sleep(4000); DeleteCriticalSection(&g_csA);
DeleteCriticalSection(&g_csB);
}DWORD WINAPI Fun1Proc(
  LPVOID lpParameter   // thread data
)
{
while(TRUE)
{
EnterCriticalSection(&g_csA);
Sleep(1);
EnterCriticalSection(&g_csB);
if(tickets>0)
{
Sleep(1);
cout<<"thread1 sell ticket : "<<tickets--<<endl;
}
else
break;
LeaveCriticalSection(&g_csB);
LeaveCriticalSection(&g_csA);
}

return 0;
}DWORD WINAPI Fun2Proc(
  LPVOID lpParameter   // thread data
)
{

while(TRUE)
{
EnterCriticalSection(&g_csB);
Sleep(1);
EnterCriticalSection(&g_csA);
if(tickets>0)
{
Sleep(1)[color=#FF0000]
;
cout<<"thread2 sell ticket : "<<tickets--<<endl;
}
else
break;
LeaveCriticalSection(&g_csA);
LeaveCriticalSection(&g_csB);
}
cout<<"thread2 is running!"<<endl;
return 0;
}但是我运行之后,每次得到的结果都不相同?所以就出现了所述的问题。难道是因为cpu是双核的原因吗?如何解释呢?
我期待你额帮助。谢谢!
[/color]

解决方案 »

  1.   

    MSDN里说的很清楚:
    Sleep
    The Sleep function suspends the execution of the current thread for the specified interval. To enter an alertable wait state, use the SleepEx function. VOID Sleep(
      DWORD dwMilliseconds   // sleep time
    );
    Parameters
    dwMilliseconds 
    [in] Specifies the time, in milliseconds, for which to suspend executionA value of zero causes the thread to relinquish the remainder of its time slice to any other thread of equal priority that is ready to run. If there are no other threads of equal priority ready to run, the function returns immediately, and the thread continues execution. A value of INFINITE causes an infinite delay. 
      

  2.   

    以前某个同学问我一个问题应用层的sleep()与内核的delay(),除了是否占用CPU以外,功能一样么?我的回答如下,在这里对你的疑惑也有会有帮助的。2.sleep()和delay()的区别最最本质的是“是否占用CPU”,占用与否的实现方式是不一样的。
    1).sleep函数的实现是通过影响进程调度,让调用sleep函数的当前进程处于睡眠状态,然后CPU会切换到其他进程继续运行,当然如 果sleep的时间足够长,CPU还会再次切换刚才调用sleep的进程,如果睡眠时间到就可以改变该进程状态继续执行该进程,如果睡眠时间 没到就不会改变该进程状态,转而切换到别的进程执行。
    2).delay函数的实现就是通过一个循环,让CPU不断的执行循环指令,这也不代表该进程就会在这段延迟时间内会一直在独占CPU,因为 进程调度模块仍在运行,所以如果延迟时间足够长以至于在延迟完成之前就发生了进程切换,那么该进程就被放入就绪队列,等待下一调度,下一次调 度到该进程的时候会继续执行循环,知道循环时间到(一般是执行n次时间精确的指令,判断n的值)。
      

  3.   


    测试结果是转交其他线程。
    当前线程sleep后,在sleep的时间内部再获得时间片,其他线程就可以获得执行机会了。