c/c++语言开发共享记一次 c 语言 的 多线程查找 简单实现

结语:有问题欢迎提在下方 ,本人在校学生,时间较为充裕, 有时间会回复的。 …

//仅供参考学习

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 preemptiven", ps->id, *(ps->isfind)); 38 printf("%s", str); 39 _endthread(); 40 } 41 if ((*cur) == ps->target) 42 { 43 printf(text("thread %d finde n"), ps->id); 44 printf(" %dn", *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 n", 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 n", 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 }

结语:有问题欢迎提在下方 ,本人在校学生,时间较为充裕, 有时间会回复的。

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/605342.html

(0)
上一篇 2021年5月13日
下一篇 2021年5月13日

精彩推荐