#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");
}