在所给线程代码的基础上,修改(1) 一个线程负责数的变化,从0变到4*3.14159,步长为0.02;(2)一个线程负责读取系统时间; (3)一个线程负责将数的正弦、余弦与正要值计算并显示,同时显示系统时间(4)步长停顿100ms。 要求:用console程序。
时间: 2024-02-21 09:59:04 浏览: 26
以下是修改后的代码实现:
```c++
#include <iostream>
#include <thread>
#include <chrono>
#include <cmath>
#include <ctime>
using namespace std;
void count_thread(double* p_count) {
double count = 0.0;
while (count < 4 * 3.14159) {
count += 0.02;
*p_count = count;
this_thread::sleep_for(chrono::milliseconds(100));
}
}
void time_thread(time_t* p_time) {
while (true) {
time(p_time);
this_thread::sleep_for(chrono::seconds(1));
}
}
void display_thread(double* p_count, time_t* p_time) {
while (true) {
double count = *p_count;
double sin_value = sin(count);
double cos_value = cos(count);
double tan_value = tan(count);
time_t current_time = *p_time;
cout << "sin(" << count << ") = " << sin_value << endl;
cout << "cos(" << count << ") = " << cos_value << endl;
cout << "tan(" << count << ") = " << tan_value << endl;
cout << "Current time: " << ctime(¤t_time) << endl;
this_thread::sleep_for(chrono::milliseconds(100));
}
}
int main() {
double count = 0.0;
time_t current_time;
thread t1(count_thread, &count);
thread t2(time_thread, ¤t_time);
thread t3(display_thread, &count, ¤t_time);
t1.join();
t2.join();
t3.join();
return 0;
}
```
其中,`count_thread` 线程负责数的变化,`time_thread` 线程负责读取系统时间,`display_thread` 线程负责将数的正弦、余弦与正要值计算并显示,同时显示系统时间。
注意,在显示时间时,使用了 `ctime` 函数将时间转换为字符串格式输出。同时需要注意,`ctime` 函数的返回值是一个指向字符串的指针,可能含有换行符等多余字符,需要进行处理。