多线程检索.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <process.h>
#include <Windows.h>
int isfind=0;
struct findinfo {
int *pstart;//首地址
int length;//长度
int findnum;//要查找的数据
int id;//编号
};
void findit(void *p) {
struct findinfo *ps = p;// 保存地址
printf("\n线程%d开始查找", ps->id);
//遍历首地址,长度10个元素
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;
}
Sleep(500);
}
printf("\n线程%d结束查找,没有找到", ps->id);
}
void main() {
int a[100] = { 0 };
time_t ts;
unsigned int data = time(&ts);
srand(data);
for (int i = 0; i < 100; i++) {
a[i] = rand() % 100;
printf("%4d", a[i]);
if ((i+1) % 10 == 0) {
printf("\n");
}
}
int num;
scanf("%d",&num);
struct findinfo info[10];//结构体数组
for (int i = 0; i < 10; i++) {
info[i].pstart = a + 10 * i;//首地址
info[i].length = 10;
info[i].id = i;
info[i].findnum = num;
HANDLE handle = _beginthread(findit, 0, &info[i]);//调用线程
//WaitForSingleObject(handle,INFINITE);
}
system("pause");
}
多线程切割.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <process.h>
#include <Windows.h>
int isfind = 0;
struct findinfo {
int *pstart;//首地址
int length;//长度
int findnum;//要查找的数据
int id;//编号
};
#define M 100 //数据
#define N 8 //线程数量
// 7 1
//100/7=14 M/(N-1) 7x14+2 M%(N-1)
void findit(void *p) {
struct findinfo *ps = p;// 保存地址
printf("\n线程%d开始查找", ps->id);
//遍历首地址,长度10个元素
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;
}
Sleep(500);
}
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 < 100; i++) {
a[i] = rand() % 100;
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;
HANDLE handle = _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;
HANDLE handle = _beginthread(findit, 0, &info[i]);//调用线程
}
//info[N-1]
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;
HANDLE handle = _beginthread(findit, 0, &info[i]);//调用线程
}
system("pause");
}