第一次听到多线程切割,笔者也没听的太懂,但发现多线程数据切割其实就是分出多个线程,进行处理查找数据的事情。而为什么切割呢,就是因为数据不够线程数分的,假如1k个数据,7个线程,这里不能够整除。所以要切割,只需要先六个线程,每个线程166个数据,然后再来个线程4个数据,便可以进行处理
想要用多线程进行数据切割检索
#define _CRT_SECURE_NO_WARNINGS
#include<Windows.h>
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
#include<time.h>
#include<process.h>
int isfind = 0;
struct findinfo {
int *pstart;
int length;
int findnum;
int id;
};
//1000个元素,1-1000
//输入N,N个线程
//查找输入num,手动
#define M 1000 //数据
#define N 7 //核
//M/(N-1) M%(N-1)
void findit(void *p) {
struct findinfo *ps = p;
printf("\n线程%d开始查找", ps->id);
for (int *pf = ps->pstart; pf < ps->pstart + ps->length; pf++) {
if (isfind == 1) {
printf("\n线程%d结束查找,其他线程已经找到", ps->id);
return;
}
if (*pf == ps->findnum) {
printf("线程%d,数据%d,地址%p", ps->id, *pf, pf);
isfind = 1;
return;
}
}
printf("\n线程%d,结束查找", ps->id);
}
void main() {
int a[M] = { 0 };
time_t ts;
unsigned int data = time(&ts);
srand(data);
for (int i = 0; i < M; i++) {
a[i] = rand() % M;
printf("%4d", a[i]);
if ((i + 1) % 10 == 0) {
printf("\n");
}
}
int num;
scanf("%d", &num);
struct findinfo info[N];
if (M%N == 0) {
for (int i = 0; i < N; i++) {
info[i].pstart = a + M/N * i;
info[i].length = M/N;
info[i].id = i;
info[i].findnum = num;
_beginthread(findit ,0, &info[i]);
}
}
else {
for (int i = 0; i < N-1; i++) {
info[i].pstart = a + M / (N-1) * i;
info[i].length = M / (N-1);
info[i].id = i;
info[i].findnum = num;
_beginthread(findit, 0, &info[i]);
}
int i = N - 1;
info[i].pstart = a + M / (N - 1) * i;
info[i].length = M % (N - 1);
info[i].id = i;
info[i].findnum = num;
_beginthread(findit, 0, &info[i]);
}
getchar();
getchar();
}
代码采用多线程分割数据,1000个数据体验不了快速,不妨变成1w,1kw或者更多,这段代码体现了多线程快速检索的思想,如果读者看到这里,不妨点赞收藏。