//仅供参考学习
1 #define _CRT_SECURE_NO_WARNINGS //屏蔽 vs 的a 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <windows.h> 5 #include <process.h> 6 #include <time.h> 7 #include <memory.h> 8 9 10 //直接改 m_MAX 的值则是改变总的范围 11 #define m_MAX 250000 //最好是 totalThread 的整数倍 12 13 14 15 typedef struct s{ 16 int *begin;//每个线程其实索引地址 17 int lenth;//索引长度 18 int target;//need find 19 int Id;//thread id 20 int *flag;//线程之间通信 21 int *isFind;//附加功能标记那个线程找到的 22 }s_t; 23 24 25 26 void find(void *p) 27 { 28 s_t* pS = (s_t*)p;//indo 29 30 int* cur = NULL;//need find number addres 31 32 for (cur = pS->begin; cur != pS->begin + pS->lenth; ++cur) 33 { 34 if (1 == *(pS->flag)) 35 { 36 char str[100] = { 0 }; 37 sprintf(str, " thread %d incapable been thread %d Preemptive ", pS->Id, *(pS->isFind)); 38 printf("%s", str); 39 _endthread(); 40 } 41 if ((*cur) == pS->target) 42 { 43 printf(TEXT("thread %d finde "), pS->Id); 44 printf(" %d ", *cur); 45 Sleep(10); 46 *(pS->flag) = 1; 47 *(pS->isFind) = pS->Id; 48 49 _endthread(); 50 } 51 } 52 {//快语句 看起来 代码整洁 53 char str[100] = { 0 }; 54 sprintf(str, " Thread %.5d is incapable ", pS->Id, *(pS->isFind)); 55 printf("%s", str); 56 } 57 58 _endthread(); 59 } 60 61 62 int main() 63 { 64 srand((unsigned int)time(NULL)); 65 66 //需要寻找的源 67 int array[m_MAX]; 68 69 //标志位 70 int flag = 0; 71 int isFind = 0; 72 73 //随机的目标 74 int target = rand() % m_MAX; 75 printf("Need find number is %d ", target); 76 77 78 int totalThread = 50; 79 80 //线程需要的信息 81 s_t s[50]; //设定线程个数 ## 这里的 50 与 totalThread 变量是相关的 要改都改 82 83 int dividedDataSize = (m_MAX / totalThread); //设定每个线程需要索引的大小 84 85 86 //随机初始化 源内的数据 87 for (int j = 0; j < m_MAX; ++j) { 88 array[j] = rand()%m_MAX; 89 } 90 91 //初始化每个线程 92 for (int i = 0; i < totalThread; ++i) 93 { 94 s[i].begin = array + (i*dividedDataSize); 95 s[i].Id = i; 96 s[i].lenth = (dividedDataSize); 97 s[i].target = target; 98 s[i].flag = &flag; 99 s[i].isFind = &isFind; 100 _beginthread(find, 0, &s[i]); 101 Sleep(10); //避免出现线程访问冲突 102 } 103 104 105 system("pause"); 106 return 0; 107 }
结语:有问题欢迎提在下方 ,本人在校学生,时间较为充裕, 有时间会回复的。