完成端口(IOCP)使用的一点想法

919阅读 0评论2011-04-18 pagx
分类:WINDOWS

其实可以通过interlocked函数来减少锁的使用的。伪代码如下

struct state_context {
    volatile LONG retry;
    volatile LONG running;
};

struct overlapped_context {
    volatile LONG finish;
    struct state_context * state; 
};

for ( ; ; ) {
    struct state_context * stp;
    struct overlapped_context * cxp;
    GetQueuedCompletionStatus(port, &count, &key, &overlapped);
    cxp = (struct overlapped_context *)overlapped; 
    stp = cxp->state;

    InterlockedExchange(&cxp->finish, 1);
    InterlockedExchange(&stp->retry, 1);

    for ( ; ; ) {

        LONG ready = InterlockedExchange(&stp->running, 1);
        if (ready != 0)
                break;

        ready = InterlockedExchange(&stp->retry, 0);
        if (ready != 0) {
            ;do something for process;
        }
        InterlockedExchange(&stp->running, 0);

        ready = InterlockedExchange(&stp->retry, 0);
        if (ready == 0)
                break;

        InterlockedExange(&stp->retry, 1);
    }
}

上一篇:一个定时器的实现
下一篇:WSAEventSelect比较靠谱的使用方法