C 简单的多线程使用

#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
#include<process.h>//多线程实现

void run(void *p) 
{
	int *xp = (int *)p;// 指针读取规则 
	char num[50] = {0};//初始化字符数组
	// 第一个参数是需要写入信息的字符数组,第二个是字符的大小 后面与printf相同的写法。
	sprintf_s(num, sizeof(num), "这里是线程%d", *xp);
	MessageBoxA(0,num,"线程", 0);//弹出消息框
}
void main(void)
{
	for (int i = 0; i < 5;i++)
	{
		//多线程启动函数,第一个是要调用的函数,第二设置栈大小0代表默认值1M,第三个参数是要传递给调用函数的值
		_beginthread(run, 0,&i );
		Sleep(10);
	}

	system("pause");
	
}

通过结构来实现多线程的数据修改与传递 

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


struct thraed
{
	int *parr;//指向需要分配的内存
	int bh;//进程编号
};

void run(void *p) 
{
	struct thraed *ptest = (struct thraed *)p;//转换指针类型
	//ptest->parr = NULL;
	
	for (int *i = ptest->parr; i < ptest->parr+1000;i++)//判断内存位置并自增
	{
		*(ptest->parr) = 1;//分配数据
		//printf("%d\n", *ptest->parr);
	}
	printf("线程编号%d完成了分配数据\n", ptest->bh);
	//Sleep(100);
	return;
}

void main(void)
{
	int*arr = NULL;
	arr= malloc(sizeof(int) * 1000000);//创建一块内存并指向
	//int arr[10] = { 0 };

	struct thraed test[100];//创建结构数组
	for (int i = 0; i < 100;i++)
	{
		test[i].parr = arr+i*1000;
		test[i].bh = i;
		_beginthread(run,0,&test[i]);//多线程调用
	}
	
	system("pause");
	free(arr);//释放内存
	system("pause");
}

 

转载于:https://my.oschina.net/u/3529405/blog/1527658

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值