0
点赞
收藏
分享

微信扫一扫

[笔记]C++知识点《四》多线程相关

phpworkerman 2022-02-21 阅读 77

文章目录

前言

以一个面试题为例子:

  1. 读取data.txt文件内容
    在这里插入图片描述

  2. 使用多线程处理

  3. 使用宏定义线程数量

第一版实现:(面试时写得答案是这个类似)

#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <iostream>
#include <memory>
#include <thread>
#include <mutex>

#define MAX_SIZE 200*1024

#define MAX_THREAD_COUNT 10




int main() {

	FILE* pFile = fopen("D:\\workspace\\vs2015\\Project1\\Debug\\data.txt","rb");

	if (!pFile) {
		printf("file open error \n");
		return -1;
	}

	char szBuff[MAX_SIZE] = { 0 };

	int i = 0;
	while (!feof(pFile)) {
		fread(&szBuff[i * 1024], 1, 1024, pFile);
		i++;
	}
		
	char szDoubleValue[8] = {0};
	int nDoubleValueIndex = 0;
	std::vector<double> vectDoubleList;
	for (size_t i = 0; i < strlen(szBuff); i++)
	{

		if (szBuff[i] == '\r') {
			float fValue = atof(szDoubleValue);
			vectDoubleList.push_back(fValue);
			//printf("%f\n", fValue);
			continue;
		}

		if (szBuff[i] == '\n') {
			nDoubleValueIndex = 0;
			memset(szDoubleValue, 0, 8);
			continue;
		}
			
		szDoubleValue[nDoubleValueIndex] = szBuff[i];
		nDoubleValueIndex++;
	}

	if (vectDoubleList.size() <= 0) {
		printf("vectDoubleList empty \n");
		return -1;
	}

	
	std::unique_ptr<std::thread> thThreadPtrList[MAX_THREAD_COUNT - 1];

	volatile int nHasProIndex = 0;
	double dTotalValue = 0;
	int size = vectDoubleList.size();
	std::mutex lock;

	long lStartTime = clock();
	for (size_t i = 0; i < MAX_THREAD_COUNT - 1; i++)
	{
		thThreadPtrList[i] = std::unique_ptr<std::thread>(
			new std::thread([&]() {
				while(1)
				{
					std::lock_guard<std::mutex> locker(lock);
					if (nHasProIndex != size) {
						dTotalValue += vectDoubleList[nHasProIndex];
						nHasProIndex++;
					}
					else {
						break;
					}
					
				}
			})
		);
	}

	while (1)
	{
		std::lock_guard<std::mutex> locker(lock);
		if (nHasProIndex != size) {
			dTotalValue += vectDoubleList[nHasProIndex];
			nHasProIndex++;
		}
		else {
			break;
		}
	}

	long lEndTime = clock();
	double dAvarageValue = dTotalValue / vectDoubleList.size();
	printf("Total Count:%d \nMedium Value:%f \nAvarage Value:%f \n", vectDoubleList.size(),vectDoubleList[vectDoubleList.size()/2], dAvarageValue);
	printf("Total Time:%d \n", lEndTime - lStartTime);

	for (size_t i = 0; i < MAX_THREAD_COUNT -1; i++)
	{
		thThreadPtrList[i]->join();
	}

	system("pause");
	return 0;
}

面试的大佬 给提了几个建议:

  1. 尽量不要用锁
  2. 尽量不要裸指针
  3. 尽量使用c++读取文件
  4. 主线程也要用上,这算小技巧
  5. 线程算法能优化,可以使用Google的map-reduces算法,类似根据线程数量把数据进行分段处理。
举报

相关推荐

0 条评论