---
title: "WaitForMultipleObjects函数有效值分析"
author: "J2EE大鸟"
date: "2013-11-01T21:19:04Z"
tags: []
categories: ["编程语言"]
slug: "waitformultipleobjects"
draft: false
lastmod: "2013-11-01T21:19:04Z"
id: 1968781
url: "https://benworld.iteye.com/blog/1968781"
---

# WaitForMultipleObjects函数存在一个固定的有效值为1~64，所以在上一篇（[http://xiabin1235910-qq-com.iteye.com/admin/blogs/1968778](/admin/blogs/1968778)）文章中，当线程数大于64时，会出现不稳定现象，如下：（此时线程数为70）

![](http://dl2.iteye.com/upload/attachment/0090/7783/6a6d91f5-e2f1-3c44-a831-fd282bc1346a.png)

如果在输出的语句之前，加上一个sleep（500）语句，则会正常，代码如下：

```
#include <windows.h>
#include <process.h>
#include <iostream>

using namespace std;

const int THREADNUM = 70;
volatile long number = 0;

unsigned int __stdcall threadFunc(PVOID pM) {
	Sleep(100);
	InterlockedIncrement(&number);
	Sleep(50);
	return 0;
}

int main() {
	int num = 20;
	
	HANDLE handle[THREADNUM];

	while(num--) {
		number = 0;
		for(int i=0; i< THREADNUM; i++) {
			handle[i] = (HANDLE)_beginthreadex(NULL, 0, threadFunc, NULL, 0, NULL);
		}
	
		WaitForMultipleObjects(THREADNUM, handle, TRUE ,INFINITE);
		Sleep(500);
		cout << "计数个数为" << number << endl;
	}
	
	getchar();
	return 0;
}
```

输出结果为：

![](http://dl2.iteye.com/upload/attachment/0090/7787/5bd035b1-7f3f-3325-8d79-ae6ebe3fc7ed.png)

所以，保险起见，在使用WaitForMultipleObjects函数时，还是要把线程数控制在64以下。

若线程数大于64，则需要考虑用别的方法。