我想在多线程程序中每秒打印当前数据队列的元素数,如下所示:
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/