改善代码#include<stdio.h> #include<windows.h> DWORD Sum1,Sum2; DWORD WINAPI Summation1(LPVOID Param) { DWORD Upper=(DWORD)Param; for(DWORD i=0;i<=Upper;i++) Sum1+=i; return 0; } DWORD WINAPI Summation2(LPVOID Param) { DWORD Upper=(DWORD)Param; for(DWORD i=0;i<=Upper;i++) Sum2+=i; return 0; } int main(int argc,char *argv[]) { DWORD ThreadId1,ThreadId2; HANDLE ThreadHandle1,ThreadHandle2; HANDLE Thread[2]; int Param1,Param2; Param1 = atoi(argv[1]); if(Param1<0) { printf("An interger parameter is required.\n"); return -1; } Param2 = atoi(argv[2]); if(Param2<0) { printf("An interger parameter is required.\n"); return -1; } ThreadHandle1 = CreateThread( NULL, 0, Summation1, &Param1, 0, &ThreadId1); ThreadHandle2 = CreateThread( NULL, 0, Summation2, &Param2, 0, &ThreadId2); Thread[0]=ThreadHandle1; Thread[1]=ThreadHandle2; if((ThreadHandle1!=NULL)&&(ThreadHandle2!=NULL)) { printf("ThreadId1=%d\n", ThreadId1); printf("ThreadId2=%d\n", ThreadId2); WaitForMultipleObjects(2,Thread,TRUE,INFINITE); CloseHandle(ThreadHandle1); CloseHandle(ThreadHandle2); printf("sum1=%d\n", Sum1); printf("sum2=%d\n", Sum2); } return 0; }
时间: 2023-07-14 10:13:45 浏览: 142
以下是改善后的代码,主要是添加了注释、修改了变量名、添加了错误处理和释放资源的代码:
```c
#include <stdio.h>
#include <windows.h>
DWORD sum1 = 0, sum2 = 0;
// 线程1的函数,计算从0到upper的整数和
DWORD WINAPI Summation1(LPVOID param) {
DWORD upper = (DWORD)param;
for (DWORD i = 0; i <= upper; i++) {
sum1 += i;
}
return 0;
}
// 线程2的函数,计算从0到upper的整数和
DWORD WINAPI Summation2(LPVOID param) {
DWORD upper = (DWORD)param;
for (DWORD i = 0; i <= upper; i++) {
sum2 += i;
}
return 0;
}
int main(int argc, char* argv[]) {
// 命令行参数转换为整数
int param1 = atoi(argv[1]);
int param2 = atoi(argv[2]);
// 检查参数是否合法
if (param1 < 0 || param2 < 0) {
printf("An integer parameter is required.\n");
return -1;
}
// 创建线程1和线程2
HANDLE threadHandle1 = CreateThread(NULL, 0, Summation1, ¶m1, 0, NULL);
HANDLE threadHandle2 = CreateThread(NULL, 0, Summation2, ¶m2, 0, NULL);
if (threadHandle1 == NULL || threadHandle2 == NULL) {
printf("Failed to create threads.\n");
return -1;
}
// 等待线程1和线程2完成
HANDLE threadHandles[2] = { threadHandle1, threadHandle2 };
DWORD waitResult = WaitForMultipleObjects(2, threadHandles, TRUE, INFINITE);
if (waitResult != WAIT_OBJECT_0) {
printf("Failed to wait for threads.\n");
CloseHandle(threadHandle1);
CloseHandle(threadHandle2);
return -1;
}
// 关闭线程句柄并输出结果
CloseHandle(threadHandle1);
CloseHandle(threadHandle2);
printf("sum1=%d\n", sum1);
printf("sum2=%d\n", sum2);
return 0;
}
```
改善后的代码添加了注释,使代码更加易读和易懂。同时,添加了错误处理和释放资源的代码,以确保程序的稳定性和健壮性。
阅读全文