试着用c写了一个多线程的同步

在Java中写多线程相关的程序简单很多,在多线程中需要同步的时候,使用synchronized就行了。

最近学习c的多线程与同步,感觉实现起来,要写的代码比较多一些,这也许是因为java封装的比较好吧。

下面是今天写的一个例子,主要参考:http://hi.baidu.com/personnel/blog/item/ae87720e8b2f5aea7acbe1c6.html

#include <stdio.h>
#include <windows.h>
#include <process.h>

//关键段变量声明
HANDLE g_hThreadEvent;
CRITICAL_SECTION g_csThreadCode;

int total = 0; //全部变量

unsigned int __stdcall threadFun(void *pm)
{
    int v = *(int *)pm;

    SetEvent(g_hThreadEvent); //触发事件

    Sleep(50);

    EnterCriticalSection(&g_csThreadCode); //进入子线程互斥区域

    total++;

    printf("thread no:%d,total:%d\n",v,total);

    LeaveCriticalSection(&g_csThreadCode); //离开子线程互斥区域

    return 0;
}

int main()
{
    //初始化事件和关键段 自动置位,初始无触发的匿名事件
    g_hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

    //关键段初始化
    InitializeCriticalSection(&g_csThreadCode);

    int i;

    int THREAD_NUM = 10; //子线程数
    HANDLE handle[THREAD_NUM];
    for(i=0;i<THREAD_NUM;i++)
    {
        handle[i] = _beginthreadex(NULL,0,threadFun,&i,0,NULL);

        WaitForSingleObject(g_hThreadEvent, INFINITE); //等待事件被触发,这里必须
    }

     WaitForMultipleObjects(THREAD_NUM, handle, TRUE, INFINITE);

     //用完之后记得销毁
     CloseHandle(g_hThreadEvent);
     DeleteCriticalSection(&g_csThreadCode);

    return 0;
}

 

运行结果:

这个例子主要测试两点:

1. 主线程与子线程的同步,使用事件(Event),参考:http://blog.csdn.net/morewindows/article/details/7445233

2. 各子线程间的同步,使用关键段(CRITICAL_SECTION),参考:http://blog.csdn.net/morewindows/article/details/7442639

另注:

实现主线程与子线程的同步,有几种方式:事件(Event)信号量(Semaphore)

实现子线程的同步,有几种方式,比如:关键段(CRITICAL_SECTION)互斥量(Mutex)

 

关于子线程间的两种同步方式的对比,参见:http://hi.baidu.com/personnel/blog/item/fd4a7609ffba398f2fddd436.html 

 

2012-05-13

 

posted @ 2015-06-17 14:32  personnel  阅读(1987)  评论(0编辑  收藏  举报
友情链接:图片批量处理工具 gif动态图制作工具 制作电子相册 图片排版工具 制作淘宝主图视频 MKScript 鼠标键盘自动化脚本语言