多线程的举例

1.多进程实现简单打印

#include<Windows.h>
#include<process.h>//进程
#include<stdlib.h>


void  run(void *p)
{
int *px = (int *)p;//指针转换
//printf("线程%d启动", *px);
char str[100] = {0};//字符数组
sprintf(str, "线程%d启动", *px);
MessageBoxA(0,str, "多线程", 0);
}

void main()
{
for (int i = 0; i < 5; i++)
{
//run(NULL);
_beginthread(run, 0, &i);

Sleep(10);//需加一定的时间缓冲,因为创建进程需要时间,不加会导致对应编号不正确
}

system("pause");
}




2.多线程实现查找

#include<stdio.h>
#include<stdlib.h>
#include<process.h>
#include<Windows.h>

int  flag = 0;//意味着没有找到
int  * addrfind = NULL;//地址
struct MyStruct
{
int *pfindstart;//要查找的首地址
int  length;//限定长度,从地址开始
int  num;//要查找的数据
int  bh;//编号
int  *pflag;//传递flag的地址,修改flag,访问
int **addr;//传递一个指针的地址,
};

void find(void *p)
{
struct MyStruct *pstruct = (struct MyStruct *)p;//指针类型转换
//内存的遍历,从地址开始累加100个元素的大小,遍历所有元素
for (int *px = pstruct->pfindstart; px < pstruct->pfindstart + 100; px++)
{
//Sleep(100);
if (*(pstruct->pflag) != 0)
{
//printf("属下%d无能,其他线程已经找到\n", pstruct->bh);
return;
}

if (*px == pstruct->num)//判断是否相等
{
printf("第%d个线程找到%p,%d\n", pstruct->bh, px, *px);//查找
*(pstruct->pflag) = 1;//改变标识,代表找到
*(pstruct->addr) = px;
return;
}
}
//printf("\n没有找到第%d个线程", pstruct->bh);

return;
}

void main2()
{
int a[1000];//783;数组
for (int i = 0; i < 1000; i++)
{
a[i] = i;//数组初始化
}
struct MyStruct threaddata[10];//创建结构体,处理不同的线程,
for (int i = 0; i < 10; i++)//创建10个线程并行查找
{
//a , a+100 a+200               a+900

threaddata[i].pfindstart = a + i * 100;//计算数组的地址
threaddata[i].length = 100;//长度
threaddata[i].bh = i;//编号
threaddata[i].num = 783;//要查找的数据
threaddata[i].pflag = &flag;//标识
threaddata[i].addr = &addrfind;//存储了变量的地址

printf("\n%d\n", threaddata[i].bh);
_beginthread(find, 0, &threaddata[i]);//


//Sleep(30);///
}


Sleep(30000);

system("pause");
printf("\n\n%d,%p\n\n", *addrfind, addrfind);//打印地址,还有数据
system("pause");
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值