多线程切割查找
初步了解多线程
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<process.h>
#include<Windows.h>
#define M 100 //数据量
#define N 8 //线程数
//保证三个线程处理的数据个数一样多,剩下一个线程处理多余的数据,
//例如:100/3=33,M/(N-1);100%3=1,M%(N-1)
int flag = 0;//假设没有找到
struct threadInfo {
int *pStart;//首地址
int length;//间隔
int key;//关键字
int threadID;//线程编号
};
void findKey(void *p) {
struct threadInfo *p1 = p;
printf("\n线程%d开始查找", p1->threadID);
for (int *p2 = p1->pStart; p2 < p1->pStart + p1->length; p2++) {
if (flag) {
printf("\n线程%d查找结束,其他线程已经找到", p1->threadID);
return;
}
if (*p2 == p1->key) {
printf("\n线程%d结束,找到数据%d,地址%p", p1->threadID, p1->key, p2);
flag = 1;
//return;//每个线程找到一个符合就退出,否则找到全部符合
}
}
printf("\n线程%d查找结束,找不到", p1->threadID);
}
void main() {
time_t ts;
srand((unsigned int)time(&ts));
int a[M] = { 0 };
//初始化数据
for (int i = 0; i < M; i++) {
printf("%3d", a[i] = rand()%100);
if ((i + 1) % 10 == 0)printf("\n");
}
printf("\n");
int key = 0;
scanf("%d", &key);
//创建线程
struct threadInfo thread[N];
if (M % N == 0) {
for (int i = 0; i < N; i++) {
thread[i].pStart = a + i * M/N;
thread[i].length = M / N;
thread[i].key = key;
thread[i].threadID = i;
HANDLE HD = _beginthread(findKey, 0, &thread[i]);
//WaitForSingleObject(HD, INFINITE);
}
}
else {
for (int i = 0; i < N-1; i++) {
thread[i].pStart = a + M / (N - 1)*i;
thread[i].length = M / (N-1);
thread[i].key = key;
thread[i].threadID = i;
HANDLE HD = _beginthread(findKey, 0, &thread[i]);
//WaitForSingleObject(HD, INFINITE);
}
int i = N - 1;//用最后一个线程处理多余的数据
thread[i].pStart = a + M / (N - 1)*i;
thread[i].length = M % (N - 1);
thread[i].key = key;
thread[i].threadID = i;
HANDLE HD = _beginthread(findKey, 0, &thread[i]);
//WaitForSingleObject(HD, INFINITE);
}
system("pause");
}