Multi-threaded Concurrent Programming Notes 07 (XiaoDi Classroom) Container

sync container

Let's write a piece of code like this.

We want to delete the vector container based on conditions when traversing:

 

 An exception will occur.

So how to write it in the correct way? This involves iterators:

 

This is what we do in a single thread.

So what about multithreading?

 

 

Sometimes it will report this error, which means that sometimes the first thread deletes demo2, and the second thread may not be able to find this element.

So how do we run it correctly?
 

We just add the synchronized keyword to the iterator.

 

We can also use the thread-safe collection methods provided by the collection class.

Concurrent containers:

 Here we mainly take CopyOnWrite as an example:

 It is possible to use this method directly in a concurrent container.

So what if we use iterators in concurrent containers?

But in a concurrent container, if we use an iterator to delete, an error will be reported to us.

 Then here we can think about how in the previous synchronization container, using a for loop to traverse and delete based on conditions in multi-threads would report an error. Will this approach still report an error in a concurrent container?

No error will be reported in concurrent containers.

 

 

Guess you like

Origin blog.csdn.net/weixin_52618349/article/details/130047975