#include<iostream> #include<Windows.h> #include <iomanip> #include <math.h> using namespace std; float x=0; DWORD WINAPI Thread1(LPVOID lpParameter); DWORD WINAPI Thread2(LPVOID lpParameter); void f1() { int i=10; while(i--) cout<<"i="<<i<<endl; } void f2() { int j=20; while(j--) cout<<"j="<<j<<endl; } int main() { cout<<"主线程已启动"<<endl; //f1(); //f2(); HANDLE hThread1=CreateThread(NULL,0,Thread1,NULL,0,NULL);//启动线程1 HANDLE hThread2=CreateThread(NULL,0,Thread2,NULL,0,NULL);//启动线程2 CloseHandle(hThread1);//关闭线程1 CloseHandle(hThread2);//关闭线程2 int i=25; while(i--) { cout<<"主线程运行中"<<endl; Sleep(100);//延时0.1s } //CloseHandle(hThread1);//关闭线程1 //CloseHandle(hThread2);//关闭线程2 system("pause");//暂停防止程序退出 return 0; } DWORD WINAPI Thread1(LPVOID lpParameter) { // cout<<"线程1已启动"<<endl; // //int i=5; // //while(i--) // //{ // //cout<<"线程1运行中"<<endl; //cout<<"i1="<<i<<endl; //Sleep(100);//延时0.1s // //} int i=0; while(i<101) { x=x+0.02; i++; Sleep(100);//延时0.1s } return 0; } DWORD WINAPI Thread2(LPVOID lpParameter) { // cout<<"线程2已启动"<<endl; // //int i=100; // //while(i--) // //{ // //cout<<"线程2运行中"<<endl; ////cout<<setw(i*10)<<"*"<<endl; //cout<<"i2="<<i<<endl; //Sleep(100);//延时0.1s // //} int i=0; while(x<=2.0) { //cout<<setw(30*sin(x))<<"*"<<endl; cout<<x<<endl; Sleep(100);//延时0.1s } return 0; }在所给线程代码的基础上,修改: (1)一个线程负责数的变化,从0变到4*3.14159,步长为0.02; (2)一个线程负责读取系统时间; (3)一个线程负责将数的正弦、余弦与正要值计算并显示,同时显示系统时间; (4)步长停顿100ms。 要求:用console程序。
时间: 2023-11-27 07:03:25 浏览: 78
好的,你的要求是让我修改所给的多线程代码。根据你的要求,我对代码进行了如下修改:
```cpp
#include<iostream>
#include<Windows.h>
#include <iomanip>
#include <math.h>
using namespace std;
float x = 0;
SYSTEMTIME st;
DWORD WINAPI Thread1(LPVOID lpParameter);
DWORD WINAPI Thread2(LPVOID lpParameter);
DWORD WINAPI Thread3(LPVOID lpParameter);
int main()
{
cout << "主线程已启动" << endl;
HANDLE hThread1 = CreateThread(NULL, 0, Thread1, NULL, 0, NULL);//启动线程1
HANDLE hThread2 = CreateThread(NULL, 0, Thread2, NULL, 0, NULL);//启动线程2
HANDLE hThread3 = CreateThread(NULL, 0, Thread3, NULL, 0, NULL);//启动线程3
CloseHandle(hThread1);//关闭线程1
CloseHandle(hThread2);//关闭线程2
CloseHandle(hThread3);//关闭线程3
int i = 25;
while (i--)
{
cout << "主线程运行中" << endl;
Sleep(100);//延时0.1s
}
system("pause");//暂停防止程序退出
return 0;
}
DWORD WINAPI Thread1(LPVOID lpParameter)
{
while (x <= 4 * 3.14159)
{
x += 0.02;
Sleep(100);//延时0.1s
}
return 0;
}
DWORD WINAPI Thread2(LPVOID lpParameter)
{
while (1)
{
GetLocalTime(&st);
Sleep(1000);//延时1s
}
}
DWORD WINAPI Thread3(LPVOID lpParameter)
{
while (1)
{
float s = sin(x);
float c = cos(x);
float t = tan(x);
cout << "sin(x)=" << s << ", cos(x)=" << c << ", tan(x)=" << t << endl;
cout << "System Time: " << st.wHour << ":" << st.wMinute << ":" << st.wSecond << endl;
cout << endl;
Sleep(100);//延时0.1s
}
return 0;
}
```
我添加了一个新的线程Thread3,负责计算sin(x)、cos(x)和tan(x)的值,并输出系统时间。同时,Thread2负责获取系统时间。Thread1则负责将x的值从0逐渐增加到4*3.14159,步长为0.02。
请注意,因为Thread3和Thread2都是无限循环的线程,所以程序需要手动结束。
阅读全文