多线程处理多个任务

#define THREAD_POOL_SIZE 3  //线程数目
#define NUM_TASKS 6 //任务数目

int main()
{
    HANDLE hThrds[THREAD_POOL_SIZE];
    int slot = 0;
    DWORD threadId;
    int i;
    DWORD rc;

    for (i=0; i < NUM_TASKS; i++)
    {
        Sleep(1000);
        /* Until we've used all threads in *
        * the pool, do not need to wait *
        * for one to exit */
        if (i >= THREAD_POOL_SIZE)
        {
            /* Wait for one thread to terminate */
            rc = WaitForMultipleObjects(THREAD_POOL_SIZE, hThrds, FALSE, INFINITE );
            
            slot = rc - WAIT_OBJECT_0;//0 to THREAD_POOL_SIZE -1
            if (slot >= 0 && slot < THREAD_POOL_SIZE)
            {
            	printf("Slot %d terminated\n", slot );
            }
            else
            {
                printf("Error or Timeout!\n");
		return 0;

            }
            if (hThrds[slot])
            {
                CloseHandle(hThrds[slot]);
                hThrds[slot] = NULL;
            }
        }

        /* Create a new thread in the given
        * available slot */

        //when slot is THREAD_POOL_SIZE, i is THREAD_POOL_SIZE too.
        //slot will be re-assigned between  0 to THREAD_POOL_SIZE -1. 
        hThrds[slot++] = CreateThread(NULL, 0, ThreadFunc, (LPVOID)slot, 0, &threadId);
        printf("Launched thread #%d (slot %d)\n", i, slot);
    }

    /* Now wait for all threads to terminate */
    rc = WaitForMultipleObjects(THREAD_POOL_SIZE, hThrds, TRUE, INFINITE );

    if (rc >= WAIT_OBJECT_0 && rc < WAIT_OBJECT_0 + THREAD_POOL_SIZE)
    {
        printf("All threads have terminated\n");
    }
    else
    {
        printf("Error or Timeout!\n");
    }
    for (slot=0; slot<THREAD_POOL_SIZE; slot++)
    {
        if (hThrds[slot])
        {
            CloseHandle(hThrds[slot]);
            hThrds[slot] = NULL;
        }
    }
    printf("All slots terminated\n");

    return EXIT_SUCCESS;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值