程序功能为主线程创建3个子线程。创建子线程1时,把字符串"This is thread 1.\n"作为参数传给子线程1;创建子线程2时,把字符串"This is thread 2.\n"作为参数传给子线程2;子线程3无传入参数。子线程1和子线程2返回时,都返回字符串"Sub thread returned.\n"给主线程;子线程3不接收返回值。各个线程在屏幕上打印相关信息。
时间: 2023-06-11 21:05:49 浏览: 93
好的,我明白了您的问题。以下是C++代码实现这个程序的功能:
```
#include <iostream>
#include <thread>
#include <string>
using namespace std;
// 定义线程1的函数
void thread1_function(string msg) {
cout << "Thread 1 prints: " << msg << endl;
// 模拟线程1的处理过程
this_thread::sleep_for(chrono::seconds(1));
cout << "Thread 1 returned." << endl;
}
// 定义线程2的函数
void thread2_function(string msg) {
cout << "Thread 2 prints: " << msg << endl;
// 模拟线程2的处理过程
this_thread::sleep_for(chrono::seconds(1));
cout << "Thread 2 returned." << endl;
}
// 定义线程3的函数
void thread3_function() {
cout << "Thread 3 started." << endl;
// 模拟线程3的处理过程
this_thread::sleep_for(chrono::seconds(1));
cout << "Thread 3 ended." << endl;
}
int main() {
// 创建线程1,传入参数"This is thread 1.\n"
thread t1(thread1_function, "This is thread 1.\n");
// 创建线程2,传入参数"This is thread 2.\n"
thread t2(thread2_function, "This is thread 2.\n");
// 创建线程3
thread t3(thread3_function);
cout << "Main thread started." << endl;
// 等待线程1和线程2执行完毕
t1.join();
t2.join();
cout << "Main thread received sub thread return value." << endl;
cout << "Main thread ended." << endl;
return 0;
}
```
您可以将这段代码复制粘贴到一个.cpp文件中,使用g++编译器进行编译。在Linux系统上,您可以执行以下命令进行编译和运行:
```
g++ -std=c++11 -pthread main.cpp -o main
./main
```
在Windows系统上,您可以使用Visual Studio或者MinGW编译器进行编译和运行。
阅读全文