我正在编写一个程序,它从一个文件 (launch.cpp) 启动多个线程,然后使用另一个文件(write.h、write.cpp)中定义的线程安全函数将字符串输出到控制台。
我相信我的函数在 write.cpp 中定义正确,但我不认为我在 launch.cpp 中正确创建线程...对于我尝试创建的每个线程,Eclipse 都会抛出实例化错误。
下面是我的代码,以及在 launch.cpp 中抛出的错误。
编写.cpp
#include <string>
#include <sstream>
#include <iostream>
#include <thread>
#include <mutex>
#include "write.h"
using namespace std;
//Mutex (only one print executes at a time)
mutex m;
//Threadsafe print functions
void PRINT1(std::string &txt) {
m.lock();
cout<<txt<<endl;
m.unlock();
}
void PRINT2(std::string &txt, std::string &txt1) {
m.lock();
cout<<txt<<txt1<<endl;
m.unlock();
}
void PRINT3(std::string &txt, std::string &txt1, std::string &txt2) {
m.lock();
cout<<txt<<txt1<<txt2<<endl;
m.unlock();
}
void PRINT4(std::string &txt, std::string &txt1, std::string &txt2, std::string &txt3) {
m.lock();
cout<<txt<<txt1<<txt2<<txt3<<endl;
m.unlock();
}
void PRINT5(std::string &txt, std::string &txt1, std::string &txt2, std::string &txt3, std::string &txt4) {
m.lock();
cout<<txt<<txt1<<txt2<<txt3<<txt4<<endl;
m.unlock();
}
启动.cpp
#include <string>
#include <sstream>
#include <iostream>
#include <thread>
#include <mutex>
#include "write.h"
using namespace std;
const string txt = "Txt";
const string txt1 = "Txt1";
const string txt2 = "Txt2";
const string txt3 = "Txt3";
const string txt4 = "Txt4";
int main() {
//Constructs threads and runs
thread t1(PRINT1, txt);
thread t2(PRINT2, txt, txt1);
thread t3(PRINT3, txt, txt1, txt2);
thread t4(PRINT4, txt, txt1, txt2, txt3);
thread t5(PRINT5, txt, txt1, txt2, txt3, txt4);
//Makes the main thread wait for the new threads to finish
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
return 0;
}
错误
最佳答案
这里有两个问题。
1) 您的 txt
变量被声明为 const
,因此非常量引用无法绑定(bind)到它们。
2) std::thread
将其参数复制(或移动)到某个内部存储中,并将这些拷贝作为右值传递给线程函数,并且非常量左值引用不能绑定(bind)到右值。
要使其工作,您需要使您的 txt
变量成为非常量并将 std::reference_wrapper
传递给 std::thread
的构造函数:
void PRINT1(std::string& txt) {
std::cout << txt << '\n';
}
std::string txt = "Txt";
int main() {
std::thread t1(PRINT1, std::ref(txt));
t1.join();
}
或者让 std::thread
复制一份,并在 PRINT
函数中接受 const
左值引用或右值引用:
void PRINT1(const std::string& txt) {
std::cout << txt << '\n';
}
const std::string txt = "Txt";
int main() {
std::thread t1(PRINT1, txt);
t1.join();
}
您选择哪个选项取决于您是否需要线程修改原始字符串。在这种情况下,由于您的所有线程都在打印字符串,因此我推荐第二个选项,因为它减少了可能的并发问题,但您应该根据实际程序的需要来选择。
关于c++ - 启动多个线程 - 实例化错误 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47213513/