• 利用关键代码段实现多线程同步


    利用关键代码段实现多线程同步

    关键代码段又叫临界区,是指一个小代码段,在代码能够执行前,它必须对具有对资源的独中权。如一次只能一个人打电话的公用电话厅,开始时要建个 电话厅(初始化临界区:InitializeCriticalSection),一个人打电话(EnterCiticalSection),打完电话离 开,便于别人打(LeaveCriticalSection),电话厅不用时,拆掉,释放资源(DeleteCriticalSection);
    如下程序实现多线程同步:
    #include <windows.h>
    #include <iostream>
    using namespace std;
    DWORD WINAPI ThreadProc1(
      LPVOID lpParameter
    );//define a thread function
    DWORD WINAPI ThreadProc2(
      LPVOID lpParameter
    );//define a thread function
    int tickets=100;//the total of tickets
    HANDLE g_hEvent;//define a handle of event
    CRITICAL_SECTION g_cs;//define a ciritical section
    int main(int argc,char** argv)
    {
     HANDLE handle1;//a thread handle
     HANDLE handle2;//a thread handle
     handle1=CreateThread(NULL,0,ThreadProc1,NULL,0,NULL);//create a thread
     handle2=CreateThread(NULL,0,ThreadProc2,NULL,0,NULL);//creat a thread
        CloseHandle(handle1);//close a thread handle
     CloseHandle(handle2);//close a thread handle
     InitializeCriticalSection(&g_cs);
        Sleep(4000);
        DeleteCriticalSection(&g_cs);
     return 0;
    }
    DWORD WINAPI ThreadProc1(
      LPVOID lpParameter
    )
    {
       while(TRUE)
       {
        EnterCriticalSection(&g_cs);
        if(tickets>0)
        {
         Sleep(2);
         cout<<"Thread1 Ticket:"<<tickets--<<endl;
        
        }
        else
         break;
        LeaveCriticalSection(&g_cs);
       }
         
     return 0;
    }
    DWORD WINAPI ThreadProc2(
      LPVOID lpParameter
    )
    {
     while(TRUE)
       {
       EnterCriticalSection(&g_cs);
        if(tickets>0)
        { 
         Sleep(2);
         cout<<"Thread2 Ticket:"<<tickets--<<endl;
        
        }
        else
         break;
        LeaveCriticalSection(&g_cs);
       }
     return 0;
    }


    WINAPI是函数调用的一种约定,等同于__stdcall,该调用约定规定,按从右至左的顺序压参数入栈,由被调用者把参数弹出栈!

  • 相关阅读:
    如何删除完全重复的列
    串联多个字符串,引发string和stringBuilder的比较
    借鉴ANJOU的方法改写了上次的TreeView
    如何改变ListBox中内容的顺序
    执行Insert语句时使用string的Format用法
    moss 2007 中FCKEditor编辑器的使用
    qt 获得cmd 命令运行的结果 GIS
    迭代器 GIS
    win32 创建带图片的button GIS
    c++标准库的构成 GIS
  • 原文地址:https://www.cnblogs.com/dongzhiquan/p/1994747.html
Copyright © 2020-2023  润新知