C ++多线程避免在函数调用期间进行交织 [英] C++ Multithreading avoiding interleaving during function calls

查看:69
本文介绍了C ++多线程避免在函数调用期间进行交织的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;
}

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

Right now this prints something like ****+++** I want it to print *** all in one line then +++ all in one line. We are not allowed to use mutex locks or block thread access to the printer function. The code must still be multithreaded.

关于如何执行此操作的任何想法?

Any ideas on how to do this?

推荐答案

累积数据,然后将其输出为一张照片:

Accumulate data and then output as one shot:

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

这篇关于C ++多线程避免在函数调用期间进行交织的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆