[C++] socket - 4 [线程同步 简单例子]

 

 

/*WINAPI 线程同步*/
#include<windows.h>
#include<stdio.h>
DWORD WINAPI myfun1(LPVOID lpParameter);//声明线程函数
DWORD WINAPI myfun2(LPVOID lpParameter);
static int a=0;
CRITICAL_SECTION Section;
int main()
{
    HANDLE h1,h2;//定义句柄变量
    InitializeCriticalSection(&Section);
    h1=::CreateThread(NULL,0,myfun1,NULL,0,NULL);//创建线程1
    printf("线程1开始运行!\r\n");
    h2=::CreateThread(NULL,0,myfun2,NULL,0,NULL);//创建线程2
    printf("线程2开始运行!\t\n");
    ::CloseHandle(h1);//关闭线程句柄对象
    ::CloseHandle(h2);
    ::Sleep(10000);
    printf("正常退出请按'q'\r\n");
    if(getchar()=='q')
    {
        DeleteCriticalSection(&Section);
    }
    else 
    {
        return 0;
    }
}
DWORD WINAPI myfun1(LPVOID lpParameter)//线程函数
{
    while(1)
    {
        EnterCriticalSection(&Section);
        a++;
        if(a<100)
        {
            printf("线程1正在计数%d\r\n",a);
            LeaveCriticalSection(&Section);
            ::Sleep(1000);
        }
        else 
        {
            LeaveCriticalSection(&Section);
            break;
        }
    }
    return 0;
}
DWORD WINAPI myfun2(LPVOID lpParameter)
{
    while(1)
    {
        EnterCriticalSection(&Section);
        a++;
        if(a<100)
        {
            printf("线程2正在计数%d\r\n",a);
            LeaveCriticalSection(&Section);
            ::Sleep(1000);
        }
        else 
        {
            LeaveCriticalSection(&Section);
            break;
        }
    }
    return 0;
}

 

posted @ 2014-03-18 14:34  beautifulzzzz  阅读(1282)  评论(0编辑  收藏  举报