双线程临界区实现

 windowsxp-vc6环境下双线程临界区实现:

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

int threadflag[2];              //线程标志
int door;                               //进入标志
long crtsec = 0;                //冲突域
HANDLE lock;                    //信号量
CRITICAL_SECTION cs;

int allnum = 100000000;
int testnum;

void indoor(int threadid)
{
        //记录线程标志
        int other = 1 - threadid;
        threadflag[threadid] = 1;
        door = threadid;

        //用户态直接判断是否可以进入
        if(threadflag[other]==1&&door!=other)
                //判断是否优先于其他线程
                if(InterlockedDecrement(&crtsec) < 0)
                        //等待信号
                        WaitForSingleObject(lock, INFINITE);

}

void outdoor(int threadid)
{
        int other = 1 - threadid;

        //用户态直接判断有无其他线程
        if(threadflag[other]==1)
                //判断是否优先于其他线程
                if(InterlockedIncrement(&crtsec) <= 0)
                        //唤醒线程
                        ReleaseSemaphore(lock, 1, NULL);

        //释放线程标志
        threadflag[threadid] = 0;

}

unsigned long __stdcall threadfunc(void * p)
{
        int temp;
        while(1)
        {
                indoor((int)p);
                //EnterCriticalSection(&cs);
                if(allnum>0)
                {
                        temp = allnum;
                        testnum++;
                        allnum = temp - 1;
                        outdoor((int)p);
                        //LeaveCriticalSection(&cs);
                }
                else
                {
                        outdoor((int)p);
                        //LeaveCriticalSection(&cs);
                        break;
                }
        }
        return 1;

}

void main()
{
        //long tt = 10;
        //InterlockedIncrement(&tt);
        HANDLE thread[2];
        //lock = CreateEvent(NULL, FALSE, FALSE, NULL);
        lock = CreateSemaphore(NULL, 0, 1, NULL);
        InitializeCriticalSection(&cs);
        thread[0] = CreateThread(NULL, 0, threadfunc, (void *)0, 0, NULL);
        thread[1] = CreateThread(NULL, 0, threadfunc, (void *)1, 0, NULL);
        WaitForMultipleObjects(2, thread, TRUE, INFINITE);
        printf("the num is %d/n", testnum);

}

结果:
the num is 100880401
Press any key to continue

不知道问题到底出在什么地方,多线程方面的高手请帮忙分析下,
至于几种同步方式的比较和测试和结果请看另一篇<线程同步的几种方法效率比较>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值