• windows编程点滴(四)之线程的同步


    MSDN -- Synchronization Functions 

    1. 使用临界区对象(CRITICAL_SECTION)

    创建线程 unsigned long _beginthreadex(void *security , unsigned stack_size,

    Unsigned(_stdcall *start_address)(void *),void *arglist, unsigned initflag,

    Unsigned *thraaddr)

    结束线程 void _endthreadex(unsigned retval);

    初始化临界区 InitializeCriticalSection(LPCRITICAL_SECTION lpCriticalSection);

    进入临界区 EnterCriticalSection( LPCRITICAL_SECTION lpCriticalSection);

    离开临界区 void LeaveCriticalSection(LPCRITICAL_SECTION lpCriticalSection);

    删除临界区 void DeleteCriticalSection(LPCRITICAL_SECTION lpCriticalSection);

    #include <windows.h>

    #include <stdio.h>

    #include <process.h>

    BOOL g_bContinue = TRUE;

    int g_nCount1 = 0;

    int g_nCount2 = 0;

    CRITICAL_SECTION g_cs;

    UINT WINAPI ThreadProc(LPVOID lpParam){

    while (g_bContinue)

    {

    EnterCriticalSection(&g_cs);

    g_nCount1++;

    g_nCount2 ++;

    LeaveCriticalSection(&g_cs);

    }

    return 0;

    }

    int main(int argc,char *argv[]){

    UINT uId;

    HANDLE hThreads[2];

    //初始化临界区

    InitializeCriticalSection(&g_cs);

    hThreads[0] = (HANDLE)_beginthreadex(NULL,0,ThreadProc,NULL,0,&uId);

    hThreads[1] = (HANDLE)_beginthreadex(NULL,0,ThreadProc,NULL,0,&uId);

    Sleep(1000);

    g_bContinue = FALSE;

    WaitForMultipleObjects(2,hThreads,TRUE,INFINITE);

    CloseHandle(hThreads[0]);

    CloseHandle(hThreads[1]);

    DeleteCriticalSection(&g_cs);

    printf("g_nCount1=%d\tg_nCount2=%d\n",g_nCount1,g_nCount2);

    return 0;

    }

    2. 互锁函数

    InterlockedIncrement InterlockedDecrement InterlockedExchangAdd InterlockedExchangePointer

    函数同步增一、减一

    LONG InterlockedIncrement(LONG volatile *Addend);

    LongInterlockedDecrement(LONG volatile *Addend);

  • 相关阅读:
    JS基本语法---while循环---练习
    JS基本语法---while循环
    JS基础语法---分支语句总结
    Python开发坦克大战
    基于Python的face_recognition库实现人脸识别
    10个Python 初学者必知编码小技巧
    论如何用python发qq消息轰炸虐狗好友
    Python + Selenium +Chrome 批量下载网页代码修改【新手必学】
    Python爬取mc皮肤【爬虫项目】
    Python 分发包中添加额外文件【新手必学】
  • 原文地址:https://www.cnblogs.com/cody1988/p/2166679.html
Copyright © 2020-2023  润新知