在启动一堆线程前,调用waitforsingleobject然后重复创建一个线程,直到wait的信号量用完,在新建线程结束时releasesemophore
希望的结果是,当一堆线成的一个结束时,可以马上创建下一个
现在的结果是只有等一堆线程都结束时,才会创建下一堆,那位大哥知道为什么?

解决方案 »

  1.   

    hSemaphore = CreateSemaphore( 
        NULL,   // no security attributes
        0,      // 这个初始值设为0
        cMax,   // maximum count
        NULL);  // unnamed semaphore
    而后有一个管理线程部分
    DWORD dwWaitResult; 
     
    // Try to enter the semaphore gate. while(1)
    {
    dwWaitResult = WaitForSingleObject( 
    hSemaphore,   // handle to semaphore
    100L);          // zero-second time-out interval switch (dwWaitResult) { 
    // The semaphore object was signaled.
    case WAIT_OBJECT_0: 
    // OK to open another window.
    cThreadCont++;
    printf("[OK]Open another thread[%d]\n", cThreadCont);
    AfxBeginThread(thread_func, NULL);
    break; 
    // Semaphore was nonsignaled, so a time-out occurred.
    case WAIT_TIMEOUT: 
    // Cannot open another window.
    continue;
    break; 
    }
    }而后在线程中
    UINT thread_func(LPVOID lpParam)
    {
            //处理......         //结束处理
    if (!ReleaseSemaphore( 
    hSemaphore,  // handle to semaphore
    1,           // increase count by one
    NULL) )      // not interested in previous count
    {
    // Deal with the error.
    printf("[*]Release Semaphore Error!\n");
    return -1;
    }
    cThreadCont --;
    return 0;
    }
      

  2.   

    最好不要让线程退出,产生一些线程而后让他们等待一个同步信号,成为一个线程库,这是服务器常用的方法,可以参考Apache2源代码。