zoukankan      html  css  js  c++  java
  • 模拟订票系统学习多线程

    #include <windows.h>
    #include <IOSTREAM.H>

    //线程函数声明
    DWORD WINAPI FuncProc1( LPVOID lpParameter//thread data
    );
    DWORD WINAPI FuncProc2( LPVOID lpParameter//thread data
    );

    //int index = 0;
    int tickets = 100;
    HANDLE hMutex; //互斥对象

    int main()
    {
    HANDLE hThread1;
    HANDLE hThread2;
    hThread1 = CreateThread(NULL,//pointer to security attributes
    0, //initial thread stack size
    FuncProc1, // pointer to thread function
    NULL, // argument for new thread
    0, // creation flags
    NULL); // pointer to receive thread ID

    hThread2 = CreateThread(NULL,
    0,
    FuncProc2,
    NULL,
    0,
    NULL);

    CloseHandle(hThread1);
    CloseHandle(hThread2);
    /*while (index++ < 1000)
    {
    cout << "main thread is running" << endl;
    }
    */

    hMutex = CreateMutex(NULL,// pointer to security attributes
    TRUE, // flag for initial ownership
    "tickets" // pointer to mutex-object name
    );

    //可以利用上用"tickets"命名来判断只能运行一个实例
    if (hMutex)
    {
    if (ERROR_ALREADY_EXISTS == GetLastError())
    {
    cout << "Only one instance can run!" << endl;
    return 0;
    }
    }

    /* 这个地方线程互斥量已在主线程中,执行下面该语句名互斥量变为2,
    则下面ReleaseMutex函数需要执行两次才能完全释放,让子线程去执行
    */
    WaitForSingleObject(hMutex,INFINITE);
    ReleaseMutex(hMutex);//此处需要释放主线程创建时得到的互斥量,否则子线程不执行
    ReleaseMutex(hMutex);//
    Sleep(4000);

    return 0 ;
    }

    //线程函数定义
    DWORD WINAPI FuncProc1(LPVOID lpParameter //thread data
    )
    {
    /*while(index++ < 1000)
    {
    cout << "thread1 is running" << endl;
    }
    */

    while(TRUE)
    {
    //ReleaseMutex(hMutex);
    WaitForSingleObject(hMutex,//handle to object to wait for
    INFINITE //time-out interval in milliseconds:INFINITE, the function's time-out interval never elapses.
    );
    if (tickets>0)
    {
    Sleep(10);
    cout << "Thread1 sell tickets: " << tickets-- << endl;
    }
    else
    {
    break;
    }
    ReleaseMutex(hMutex);
    }

    return 0;
    };

    DWORD WINAPI FuncProc2( LPVOID lpParameter//thread data
    )
    {
    while(TRUE)
    {
    //ReleaseMutex(hMutex);
    WaitForSingleObject(hMutex,INFINITE);
    if (tickets>0)
    {
    Sleep(10);
    cout << "Thread2 sell tickets: " << tickets-- << endl;
    }
    else
    {
    break;
    }
    ReleaseMutex(hMutex);
    }

    return 0;
    }
  • 相关阅读:
    LayoutInflater介绍及例子
    Java对象转换为Json对象
    重写Object.equals()方法和Object.hashCode()方法
    初步理解一下:SOA, SOAP, Web Service, WSDL等
    JSP九大内置对象及四个作用域
    Visual Studio的导入和导出设置
    winform三态树的构建和使用
    关于android编程使用android.hardware.Camera 方向不对的问题
    xampp软件包如何重置mysql的 密码
    有关.NET中的config文件的一些问题
  • 原文地址:https://www.cnblogs.com/kernel0815/p/2390377.html
Copyright © 2011-2022 走看看