如何从线程返回少量字符串并将其链接到一个字符串? 我在Windows窗体中使用CLI / C ++,线程。此代码应将消息从用户划分为n(nThreads)文本,并在每个线程中应加密消息。 最后,它必须将所有结果汇总为一个。
其实我做过这样的事情:
public: ref class ThreadExample
{
public:
static String^ inputString;
static String^ outputString;
static array<String^>^ arrayOfThreads = gcnew array <String^>(nThreads);
static int iterator;
static void ThreadEncipher()
{
string input, output;
MarshalString(inputString, input);
output = CaesarCipher::encipher(input);
outputString = gcnew String(output.c_str());
arrayOfThreads[iterator] = outputString;
}
我使用线程的函数:
array<String^>^ ThreadEncipherFuncCpp(int nThreads, string str2){
array<String^>^ arrayOfThreads = gcnew array <String^>(nThreads);
string loopSubstring;
messageLength = str2.length();
int numberOfSubstring = messageLength / nThreads;
int isModulo = messageLength % nThreads;
array<Thread^>^ xThread = gcnew array < Thread^ >(nThreads);
int j;
//loop dividing text to threads
for (int i = 0; i < nThreads; i++)
{
j = i;
if (i == 0 && numberOfSubstring != 0)
loopSubstring = str2.substr(0, numberOfSubstring);
else if ((i == nThreads - 1) && numberOfSubstring != 0){
if (isModulo != 0)
loopSubstring = str2.substr(numberOfSubstring*i, numberOfSubstring + isModulo);
else
loopSubstring = str2.substr(numberOfSubstring*i, numberOfSubstring);
}
else if (numberOfSubstring == 0){
loopSubstring = str2.substr(0, isModulo);
i = nThreads - 1;
}
else
loopSubstring = str2.substr(numberOfSubstring*i, numberOfSubstring);
xThread[i] = gcnew Thread(gcnew ThreadStart(&ThreadExample::ThreadEncipher));
}
auto start = chrono::system_clock::now();
for (int i = 0; i < nThreads; i++){
ThreadExample::iterator = i;
ThreadExample::inputString = gcnew String(loopSubstring.c_str());
xThread[i]->Start();
}
for (int i = 0; i < nThreads; i++){
xThread[i]->Join();
}
auto elapsed = chrono::system_clock::now() - start;
long long milliseconds = chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
cppTimer = milliseconds;
arrayOfThreads = ThreadExample::arrayOfThreads;
delete xThread;
return arrayOfThreads;
}
答案 0 :(得分:0)
我打算在这里猜一下,并说程序运行没有错误,但你的输出是空白的。
输出为空的原因是静态类初始值设定项。这比你想象的更早执行:只要你以任何方式引用类,静态初始化程序就会运行。因此,当您尝试执行ThreadExample::inputString = "Some example text. Some example text2.";
时,静态类初始化程序已经运行,并且您的线程数组已设置。
要解决此问题,请将该代码移出静态初始值设定项,然后移到创建线程的方法中。
此外,关于C ++ / CLI的更一般说明:如果您正在尝试学习C ++,请不要使用C ++ / CLI。 C ++ / CLI 不与C ++相同。 C ++ / CLI具有C ++的所有复杂性,C#的所有复杂性,以及它自身的一些复杂性。当需要将.Net代码与C ++代码接口而不是作为主要开发语言时,应该使用它。