多线程切割查找(数据切割)

多线程切割查找

初步了解多线程

#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");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值