Obtain the number of CPUs in Linux to determine the number of multi-threads

In actual projects, especially on the server side, multiple threads are required to process business. In addition to configuring the thread number in the configuration file, we can also determine or even allocate the number of threads according to the number of system CPUs.

int GetProcessorNum()
{

	FILE *fstream=NULL;
	char buff[1024];
	memset(buff,0,sizeof(buff));
	if (NULL == (fstream = popen("grep 'processor' /proc/cpuinfo | sort -u | wc -l", "r")))
	{
		return -1;
	}

	fgets(buff, sizeof(buff), fstream);
	int kProcessorNum = atoi(buff);

	pclose(fstream);

	printf("GetProcessorNum = [%d].\n", kProcessorNum);
	return kProcessorNum ;
}

 

Guess you like

Origin blog.csdn.net/Swallow_he/article/details/88867175