修改了孙鑫的那本书的代码,原来的代码有BUG。

最明显的一个是,互斥对象在需要互斥的线程之前就应该创建,否则会出问题。

 

// File: MultiThread.cpp
// Description: Tickets selling simulation

#include 
<windows.h>
#include 
<iostream>
#include 
<cstdlib>
#include 
<ctime>
using namespace std;

DWORD WINAPI Fun1Proc( LPVOID lpParameter  
/* Thread data */ );
DWORD WINAPI Fun2Proc( LPVOID lpParameter 
/* Thread data */ );

int index = 0;
int tickets = 100;
const int nMaxWaitTime = 400;
const int nProcessTime = 0;
HANDLE hMutex;

int main()
{
    HANDLE hThread1;
    HANDLE hThread2;

    hMutex 
= CreateMutex( NULL, FALSE, NULL );

    srand( time(NULL) );

    
// Create threads
    hThread1 = CreateThread( NULL, 0, Fun1Proc, NULL, 0, NULL );
    hThread2 
= CreateThread( NULL, 0, Fun2Proc, NULL, 0, NULL );

    WaitForSingleObject( hThread1, INFINITE );
    WaitForSingleObject( hThread2, INFINITE );
    CloseHandle( hThread1 );
    CloseHandle( hThread2 );

    cout 
<< "Tickets out." << endl;

    
return 0;
}

//Entry of Fun1Proc
DWORD WINAPI Fun1Proc( LPVOID lpParameter /* Thread data */)
{
    
while (TRUE)
    {
        Sleep( rand() 
% nMaxWaitTime );
        WaitForSingleObject( hMutex, INFINITE );
        Sleep( nProcessTime );
        
if ( tickets > 0 )
            cout 
<< "Thread1 sell ticket : " << tickets-- << endl;
        
else 
            
break;
        ReleaseMutex( hMutex );
    }
    
return 0;
}

// Entry of Fun2Proc
DWORD WINAPI Fun2Proc( LPVOID lpParameter /* Thread data */ )
{

    
while ( TRUE )
    {
        Sleep( rand() 
% nMaxWaitTime );
        WaitForSingleObject( hMutex, INFINITE );
        Sleep( nProcessTime );
        
if ( tickets > 0 )
            cout 
<< "Thread2 sell ticket : " << tickets-- << endl;
        
else
            
break;
        ReleaseMutex( hMutex );
    }
    
return 0;
}

//End of file MultiThread.cpp

相关文章:

  • 2022-12-23
  • 2021-11-17
  • 2021-11-27
  • 2021-05-01
  • 2022-02-05
  • 2022-12-23
  • 2022-01-06
  • 2021-10-10
猜你喜欢
  • 2022-12-23
  • 2021-11-08
  • 2021-08-29
  • 2022-12-23
  • 2022-01-05
  • 2021-06-26
  • 2022-12-23
相关资源
相似解决方案