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

ban*_*nas 6 c++ multithreading

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;
}
Run Code Online (Sandbox Code Playgroud)

现在这打印像****+++**我希望它在一行中打印***然后+++全部在一行中.我们不允许使用互斥锁或阻止线程访问打印机功能.代码仍然必须是多线程的.

关于如何做到这一点的任何想法?

das*_*ght 11

给每个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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • @drescherjm实际上从c ++ 11开始,可以同时使用`cout` (2认同)

Sla*_*ica 9

累积数据然后输出为一次:

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