这段代码模拟两个售票点卖票,共100张票,两个售票点就作为两个线程,现在的问题是经常出现某张票被线程1卖了两次的情况:
比如:thread1 is selling tickets100
      thread1 is selling tickets100
这句话打印出了两次 不就是同一张票被同一站点卖了两次么? 这段代码和孙鑫的vc详解上完全一样的,可是运行结果怎么不一样呢?#include <windows.h>
#include <iostream.h>
DWORD WINAPI thread1(LPVOID lpParamater);
DWORD WINAPI thread2(LPVOID lpParameter);
int tickets = 100;
HANDLE hMutex;DWORD WINAPI thread1(LPVOID lpParamater)
{
   
while(TRUE)
{   
    WaitForSingleObject(hMutex, INFINITE);
    if(tickets > 0)
    {   
cout << "thread1 is selling tickets" << tickets-- << endl;
     }
    else
    {
break;
     }
   ReleaseMutex(hMutex);
}

return 0;
}DWORD WINAPI thread2(LPVOID lpParamater)
{
    
while(TRUE)
{   
    WaitForSingleObject(hMutex, INFINITE);
    if(tickets > 0)
    {
cout << "thread2 is selling tickets" << tickets-- << endl;
     }
    else
    {
break;
     }
    ReleaseMutex(hMutex);
}

return 0;
}
int main()
{
         HANDLE handle1, handle2;
handle1 = CreateThread(NULL, 0, thread1, NULL, 0, NULL);
handle2 = CreateThread(NULL, 0, thread2, NULL, 0, NULL);
         CloseHandle(handle1);
CloseHandle(handle2);
hMutex = CreateMutex(NULL, FALSE, NULL);   
Sleep(20);
return 0;
}

解决方案 »

  1.   


    hMutex = CreateMutex(NULL, FALSE, NULL);   最好放在线程定义之前就初始化。
      

  2.   

    不是每次都出现问题的,但是我这里每次线程1都会先执行两三次,而且这两三次有时打印出来的是一样的就比如说:thread1 is selling tickets100
         thread1 is selling tickets100
    然后线程1和线程2才开始交替执行,这是怎么回事啊
      

  3.   

    volatile int tickets = 100;
    另外 break执行后ReleaseMutex(hMutex);没有执行;
      

  4.   

    在线程启动前就应该建立互斥对象
    主函数改为:
    int main()
    {
      HANDLE handle1, handle2;
    hMutex = CreateMutex(NULL, FALSE, NULL);  
    handle1 = CreateThread(NULL, 0, thread1, NULL, 0, NULL);
    handle2 = CreateThread(NULL, 0, thread2, NULL, 0, NULL);
      CloseHandle(handle1);
    CloseHandle(handle2);Sleep(20);
    return 0;
    }