C++多线程在函数调用期间避免交错

C++ Multithreading avoiding interleaving during function calls

本文关键字:多线程 函数调用 C++      更新时间:2023-10-16
int main() {
thread t1([] {printer("*", 100); });
thread t2([] {printer("+", 100); });
t1.join();
t2.join();
}
void printer(string c, int num)
{
for (int i = 1; i <= num; i++)
{
cout << c;
}
cout << endl;
}

现在,它打印类似***++***的内容。我希望它在一行中打印***所有内容,然后在一行打印+++所有内容。我们不允许使用互斥锁或阻止线程访问打印机函数。代码必须仍然是多线程的。

有什么想法吗?

给每个printer自己的缓冲区,并打印main:的结果

void printer(ostream& oss, string c, int num) {
for (int i = 1; i <= num; i++) {
oss << c;
}
}
int main() {
stringstream s1, s2;
thread t1([&] {printer(s1, "*", 10); });
thread t2([&] {printer(s2, "+", 10); });
t1.join();
t2.join();
cout << s1.str() << s2.str() << endl;
return 0;
}

main为每个线程准备单独的输出缓冲区,让每个线程同时填充其缓冲区,并等待线程完成。一旦两个线程都返回,main就会将结果打印到cout

累积数据,然后一次性输出:

void printer(string c, int num)
{
std::string buff;
for (int i = 1; i <= num; i++)
buff += c;
cout << buff << endl;
}

首先写入字符串流而不是直接输出将解决同步问题:

#include <iostream>
#include <string>
#include <sstream>
#include <thread>
void printer(std::string c, int num) {
std::stringstream strm;    
for (int i = 1; i <= num; i++) {
strm << c;
}
std::cout << strm.str() << std::endl;
}
int main() {
std::thread t1([] {printer("*", 100); });
std::thread t2([] {printer("+", 100); });
t1.join();
t2.join();
}

让主线程在启动t2:之前等待t1

thread t1([] {printer("*", 100); });
t1.join();
thread t2([] {printer("+", 100); });
t2.join();