C++多线程在函数调用期间避免交错
C++ Multithreading avoiding interleaving during function calls
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();
相关文章:
- 如何在大函数中编写多线程函数?
- 在多线程函数中返回共享的常量指针会导致计时问题吗?
- 具有多线程支持的 RenderClass,将函数调用推送到向量以在另一个线程上调用
- 对象析构函数在多线程处理时不断被调用,但该对象并未超出范围
- gdb:在多线程程序中调用函数,不进行线程
- 为什么我在C++线程函数调用中得到重复值?
- C++多线程在函数调用期间避免交错
- TBB C++多线程错误:没有匹配的调用函数
- 在多线程中调用带有输入参数的函数
- 多线程:何时调用互斥锁
- 为什么函子的 dtor 在作为函数的参数传递给线程时调用两次(多次)
- 通过引用使用参数进行 C++ 多线程函数调用
- 多线程JNI调用
- LuaPlus:如何从多线程C++中调用Lua函数
- QML是否与多线程/异步调用兼容
- 多线程和得到一个错误调用函数
- 在多线程循环中调用函数
- 将单个整数传递给c++中的多线程函数
- C++多线程函数在Linux和Windows中具有包容性和排他性
- 从 Java 的多线程并行调用非线程安全的 DLL 函数