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

时间:2017-10-18 20:07:56

标签: 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;
}

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

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

4 个答案:

答案 0 :(得分: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;
}

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

答案 1 :(得分:9)

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

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

答案 2 :(得分:3)

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

#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();
}

答案 3 :(得分:2)

在开始t1之前让主线程在t2等待:

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