Is there any threadsafe queue?

Bienlein via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 14 07:36:52 UTC 2017


On Wednesday, 13 September 2017 at 07:51:19 UTC, John Burton 
wrote:
> Is there any threadsafe queue in the standard library?
> I've not been able to find anything but thought I'd check 
> before making my own.
>
> I want to be able to assemble messages (Which are just streams 
> of bytes) in one thread into a struct and push them to the 
> queue, and then have a another thread be able to read and 
> process the messages. Single producer and consumer.

You can take some existing container and overwrite the add and 
remove methods to be synchronized, e.g.

public void add(T t) {
	synchronized {
		super.add(t);
	}
}

However, this could cause some lock contention depending on your 
use case. This is why class Vector in Java is basically 
discontinued. In that class every method is synchronized which 
has led to bad timing behavior. For the new concurrent 
collections in Java since Java 5 some work has been done to 
replace synchronized with some CAS approach. For example, class 
ConcurrentLinkedQueue in Java does some tricks with CAS 
algorithms to get around this.




More information about the Digitalmars-d-learn mailing list