1 #include <Windows.h> 2 3 DWORD WINAPI my_message(void *p) 4 { 5 MessageBoxA(0, "hello", "china", 0); 6 7 return 0; 8 } 9 10 void main() 11 { 12 HANDLE hthread; 13 DWORD threadid;//保存线程的编号 14 15 for (int i = 0; i < 5; i++) 16 { 17 hthread = CreateThread( 18 NULL,//安全属性 19 NULL,//堆栈大小 20 my_message,//线程的入口点 21 NULL,//函数的参数 22 0,//立即执行 23 &threadid);//保存线程的编号 24 25 WaitForSingleObject(hthread, INFINITE);//等待 执行完再执行下一个 26 } 27 28 system("pause"); 29 }
另一种方法实现多线程
1 #define _CRT_SECURE_NO_WARNINGS 2 #include <stdlib.h> 3 #include <stdio.h> 4 #include <process.h> 5 #include <Windows.h> 6 #include <string.h> 7 8 //多线程函数 9 void pro(void *p) 10 { 11 char str[100]; 12 int *num = (int *)p; 13 sprintf(str, "%d", *num); 14 MessageBoxA(0, str, "多线程", 1); 15 } 16 17 void main() 18 { 19 for (int i = 0; i < 10; i++) 20 { 21 HANDLE hd = (HANDLE)_beginthread(pro, 0, &i); 22 //WaitForSingleObject(hd,INFINITE); 23 //等待当前线程执行完再执行下一个线程 24 } 25 26 system("pause"); 27 }
多线程切割实现数值计算
1 #define _CRT_SECURE_NO_WARNINGS 2 #include <stdlib.h> 3 #include <stdio.h> 4 #include <process.h> 5 #include <Windows.h> 6 #include <time.h> 7 #define N 1000 8 9 //每个线程的信息 10 struct Myinfo 11 { 12 int id;//线程编号 13 int *pstart;//开始地址 14 int length;//长度 15 int sum;//存储数据的和 16 }; 17 18 //多线程函数 19 void add(void *p) 20 { 21 struct Myinfo *pinfo = (struct Myinfo *)p; 22 //根据线程信息求出相应的值 23 for (int i = 0; i < pinfo->length; i++) 24 { 25 pinfo->sum += pinfo->pstart[i]; 26 } 27 printf("线程%d计算结果%d ", pinfo->id, pinfo->sum); 28 } 29 30 31 void main() 32 { 33 //初始化随机数种子 34 time_t ts; 35 unsigned int num = time(&ts); 36 srand(num); 37 int data[N] = { 0 }; 38 //随机初始化数组 39 for (int i = 0; i < N; i++) 40 { 41 data[i] = rand() % 1000; 42 } 43 44 45 46 struct Myinfo info[8] = { 0 }; 47 48 //开启八个进程 49 for (int i = 0; i < 8; i++) 50 { 51 info[i].id = i; 52 info[i].length = N / 8; 53 info[i].sum = 0; 54 info[i].pstart = data + i*N / 8; 55 _beginthread(add, 0, &info[i]); 56 } 57 58 //求出总和 59 Sleep(1); 60 int lastsum = 0; 61 for (int i = 0; i < 8; i++) 62 { 63 lastsum += info[i].sum; 64 } 65 66 printf("多线程总结果;%d ", lastsum); 67 system("pause"); 68 }