VC 多线程使用临界区

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/earbao/article/details/23352451
// CsTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>

int g_Num_One = 0;
CRITICAL_SECTION g_cs;

DWORD WINAPI ThreadProc(LPVOID lpParam)
{

    int nTmp = 0;
	int i = 0;
    for (i = 0; i < 10; i ++ )
    {
		//注释掉临界区,全局变量数据会乱,在临界区只允许一个线程进来执行
        EnterCriticalSection(&g_cs);
        nTmp = g_Num_One;
        nTmp ++;
        Sleep(1);
        g_Num_One = nTmp;
		printf("%d %d\n",g_Num_One,nTmp);
        LeaveCriticalSection(&g_cs);
		//每条线程循环10次
    }
	//printf("线程执行");
    return 0;
}

int main(int argc, char* argv[])
{
    InitializeCriticalSection(&g_cs);
    HANDLE hThread[10] = { 0 };
	int i = 0;
    for (i = 0; i < 10; i ++)
    {
        hThread[i] = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
        if ( hThread[i] == NULL )
        {
            printf("%d CreateThread Error \r\n", i);
        }
    }

    WaitForMultipleObjects(10, hThread, TRUE, INFINITE);

    printf("%d \r\n", g_Num_One);
    
    for ( i = 0; i < 10; i ++ )
    {
        CloseHandle(hThread[i]);
    }
    DeleteCriticalSection(&g_cs);
	system("pause");

	return 0;
}

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页