c++ - 以线程安全方式每秒打印当前队列元素数

标签 c++ multithreading

我想在多线程程序中每秒打印当前数据队列的元素数,如下所示:

queue<int> products;
void print(ostream& s)
{
    cout << s.rdbuf();
    cout.flush();
    s.clear();
}
void printQueue()
{
    while(true)
    {
        this_thread::sleep_for(chrono::seconds(1));
        print(stringstream() << "Number of prouducts: " << products.size() << "\n");
    }
}

void producer(int i)
{ //adds data into queue in thread safe manner
}
void consumer(int i)
{/*removes data from queue in thread safe manner*/}

int main()
{
  vector<thread> thrds;

    for(int i = 0; i < 5; ++i)
        thrds.push_back(thread(producer, i));

    for(int i = 0; i < 4; ++i)
        thrds.push_back(thread(consumer, i));

     thrds.push_back(thread(printQueue));

    for(auto& t : thrds)
        t.join();
}
return 0;
}

printQueue - 这个函数线程安全吗?

最佳答案

有两种资源被多线程访问:

  • std::cout
  • 产品

std::cout 的典型实现相对难以被多线程访问,尽管它们不保证输出不是例如交错的。尽管如此,形式上没有同步,所以您的写入不是线程安全的。

关于 products,您在那里的访问也不受任何互斥锁保护,这也使这些访问成为非线程安全的。在某些地方你只看尺寸并不重要。并不是说这种读取访问会破坏任何东西,但结果(即当您看到更改和看到的内容时)仍然是未定义的。

总结:使用互斥量来保护共享资源。

关于c++ - 以线程安全方式每秒打印当前队列元素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34952481/

相关文章:

c - 使用带有线程的 C 套接字来读取和写入套接字时出现问题

java - 线程意外工作

java - 异步执行多个java方法并获取完成工作的结果

c++ - 在头文件中初始化可自定义结构的 vector

c++ - 如何查询和更改QToolTip 出现的时间?

c++ - switch 语句中的静态变量

c++ - 如何在高于 2D 的维度上旋转、旋转、螺旋

c++ - Makefile: multiple definition and undefined reference 错误

c# - 为 Thread.Sleep(TimeSpan) 设置高值

java - ConcurrentHashMap迭代保证