现在的位置: 首页 > 综合 > 正文

线程并发,用标志位同步时要小心

2013年03月03日 ⁄ 综合 ⁄ 共 582字 ⁄ 字号 评论关闭
线程并发,用标志位同步时要小心

static INT bUseCount = 0;

static void socket_startup()
{
    WSADATA wsaData;
    WORD wVersionRequested = MAKEWORD(2,2);

    if (bUseCount++ == 0) {
        WSAStartup(wVersionRequested, &wsaData);
    }
}

int socket_create(int domain, int type)
{
    socket_startup();
    return socket(domain, type, 0);
}

void proc_0(void * params)
{
    int fd_listen;
    fd_listen = socket_create(1, SOCK_STREAM);
    ...
}

_beginthread(proc_0, 0, 0);
_beginthread(proc_1, 0, 0);
_beginthread(proc_2, 0, 0);

三个线程并发,调用socket之前WSAStartup可能未执行!
对变量的访问加锁可解决这个问题
mutex.Lock();
if (bUseCount++ == 0) {
    WSAStartup(wVersionRequested, &wsaData);
}
mutex.Unlock();

抱歉!评论已关闭.