线程生产者和消费者 [英] Thread Producer and Consumer

查看:117
本文介绍了线程生产者和消费者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的控制台应用程序,用于维护对象队列.对队列的所有访问都应以线程安全的方式处理.在启动时,应用程序应提示用户输入要创建的生产者线程和使用者线程的数量,默认为每个线程两个.然后,应用程序应产生适当数量的生产者线程和消费者线程.

每个生产者线程都应该位于一个循环中,每次++迭代创建一个新对象,并将其添加到队列中. (这不必是一个紧密的循环;否则,队列可能增长得太快而无法监视.)

每个使用者线程应坐在一个循环中,尝试在每次迭代时从队列中删除一个对象.它应该在每次迭代中向控制台写一行文本,其中包含时间戳,对象的字符串表示形式,创建对象的生产者线程的ID和显示对象的使用者线程的ID.如果队列为空,则只需将时间戳和"EMPTY"写入控制台.

该应用程序应运行,直到用户按下ENTER键.在关闭时,应用程序应确保所有生产者和使用者线程都已关闭,然后显示队列中剩余的所有对象,等待用户在关闭前再次按ENTER.

simple console application that maintains a queue of objects. All access to the queue should be handled in a thread-safe manner. At startup, the application should prompt the user for the number of producer and consumer threads to create, defaulting to two of each. The application should then spawn the appropriate number of producer and consumer threads.

Each producer thread should sit in a loop, creating a new object each++ iteration and adding it to the queue. (This does not need to be a tight loop; otherwise the queue could grow too quickly to monitor.)

Each consumer thread should sit in a loop, attempting to remove an object from the queue on each iteration. It should write a line of text to the console each iteration that contains a time stamp, a string representation of the object, an id for the producer thread that created the object, and an id for the consumer thread that displayed the object. If the queue is empty, just a time stamp and "EMPTY" should be written to the console.

The application should run until the user hits the ENTER key. At shutdown, the application should make sure all producer and consumer threads shut down, then display any objects left in the queue, waiting for the user to hit ENTER again before closing.

推荐答案

这看起来像是作业.

最好自己做作业.它是给您的,以便您将学到一些东西,思考所学的内容.阅读教科书并尝试一下.
看看这个维基:生产者-消费者问题 [
This looks like homework.

It would be best if you did your own homework. It is given to you so that you will learn something, think about what have been taught. Read your text books and give it a try.
Have a look at this wiki: Producer-consumer problem[^]

Once you have code and run into problems you can always come back here with a more specific question and the community will do its best to help you. Don''t forget to post only the relevant code bits that pose the problem as a code dump is not usually helpful at all in getting someone to help/assist you.


这篇关于线程生产者和消费者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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