473,395 Members | 1,578 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

STL (std) thread safety issues

These questions apply to std vector, map, and cout:

I am uncertain of the thread safety for reading/writing
for std templates. I know if all threads are reading
concurrently, it is thread safe. However, I have this situation:

Case 1: map

thread 1
---------
someMapOb [key] = value //inserting new pair

thread 2
---------

interator pos;

while (1==1)
{
for (pos = someMapOb.begin(); pos != someMapOb.end(), pos++ )
{
someValueOb = pos->second;

someValueOb.foo ();

}

sleep (1)
{
Is safe for case 1 if I do that? I don't care
if I miss a new inserted object in thread 2.
If a new object inserted into the map, will the
iterator be invalidated?
The reason that I omit a mutex is to maximize performance.

---------------
Case 2: queue

thread 1
--------
someQueue.push ( value );

thread 2
---------
while ( ! someQueue.isEmpty ()
{
// display a status indicator
// NOte, I don't pop or push the Q here
}
Is safe to call isEmpty() while the Q is being
pushed?

--------------------------

Case 3: cout

thread 1
--------
cout << "Thank you in advance for your help!" << endl;

thread 2
---------
cout << "Display....display ....." << endl;

I know the screen output might be messed up,
but would this concurrent cout cause a buffer overfloat
crash?

Thank you vey much for your help!
I look forward to hear from your solutions.


Jul 22 '05 #1
3 17764
Philip V Pham wrote:
These questions apply to std vector, map, and cout:

I am uncertain of the thread safety for reading/writing
for std templates. I know if all threads are reading
concurrently, it is thread safe. However, I have this situation:

<snip>

Please don't multipost. If you must post in multiple groups, crosspost.
Standard C++ does not support threading, so your question is off topic for
this group. Please ask in a group for your implementation.

- Pete
Jul 22 '05 #2
STL has no built in thread support, so you'll have to extend the STL
code with your own synchronization mechanisms to use STL in
a multithreaded environment. Case1 and Case2 are clearly
unsafe in my opinion. One of the troubles with thread programming
is things can appear to work correctly in development, but strange
bugs appear in the field when the execution environment can vary .
You need to apply very strict logical reasoning
in thread programming and be very conservative in your assumptions.
After that, test your code on a multiprocessor machine.
Case 1 - this is not thread safe, thread 1 may be preempted
while performing the insertion, leaving the map in an undefined state,
iteration over the map would be undefined. Inserting an element into
a map rearranges the internal arrangement of elements, so if this is
preempted
the internal arrangement may not be in a valid state.

You might want to look at the double-locking pattern which provides
a more efficient mechanism to deal with locking shared data structures.
Basically, a flag is set/reset to indicate a lock mutex lock is in place, if
the flag is set, then thread gives up and try again later, otherwise the
thread
proceeds to acquire the lock and set the flag. This attempts to avoid the
costly
operation of trying to acquire the lock and failing.

I'd have to look it up, but I think the map iterators would not be
invalidated, that
is an iterator would still "point" to the same element after an insertion,
just
that the internal links to its neighbours could be different, - again, if
the rearrangment
of the elements is preempted, imagine what chaos will result if you try to
iterate
over the elements...!
case 2 - again, this is unlikely to work, the push operation is non-atomic
so could be preempted mid-way, so you might have a situation where an
element has been inserted intot the queue but the count of elements hasn't
been updated...I in your example this is "harmless"situation, but I don't
think I'd like
to have it in my fly-by-wire navigation system
case 3 - I don't know - cout could be implemented to serialize the two
calls, but might not be for performance reasons with different
implementations.

dave

"Philip V Pham" <pv******@yahoo.com> wrote in message
news:Eg*****************@newssvr16.news.prodigy.co m...
These questions apply to std vector, map, and cout:

I am uncertain of the thread safety for reading/writing
for std templates. I know if all threads are reading
concurrently, it is thread safe. However, I have this situation:

Case 1: map

thread 1
---------
someMapOb [key] = value //inserting new pair

thread 2
---------

interator pos;

while (1==1)
{
for (pos = someMapOb.begin(); pos != someMapOb.end(), pos++ )
{
someValueOb = pos->second;

someValueOb.foo ();

}

sleep (1)
{
Is safe for case 1 if I do that? I don't care
if I miss a new inserted object in thread 2.
If a new object inserted into the map, will the
iterator be invalidated?
The reason that I omit a mutex is to maximize performance.

---------------
Case 2: queue

thread 1
--------
someQueue.push ( value );

thread 2
---------
while ( ! someQueue.isEmpty ()
{
// display a status indicator
// NOte, I don't pop or push the Q here
}
Is safe to call isEmpty() while the Q is being
pushed?

--------------------------

Case 3: cout

thread 1
--------
cout << "Thank you in advance for your help!" << endl;

thread 2
---------
cout << "Display....display ....." << endl;

I know the screen output might be messed up,
but would this concurrent cout cause a buffer overfloat
crash?

Thank you vey much for your help!
I look forward to hear from your solutions.

Jul 22 '05 #3
"Dave Townsend" <da********@comcast.net> wrote:
STL has no built in thread support, so you'll have to extend the STL
code with your own synchronization mechanisms to use STL in
a multithreaded environment.
It is correct that the c++ standard does not require any multi-threading
capabilities. However, implementations for multi-threaded environments
typically have some support for multi-threading. In general, it is safe
to read data structures from multiple threads but changing a data
structure is allowed only for a thread with exclusive access to the data
structure. Note that you typically have to inject some form of
synchronization device after writing a data structure (eg. a mutex release)
even if you can guarantee that the data structure is not accessed from
multiple threads due to timing constraints: especially on multi processor
systems the modified data is not always visible to other processors until
it is explicitly written back.
Case1 and Case2 are clearly unsafe in my opinion.
All three cases are unsafe.
You might want to look at the double-locking pattern which provides
a more efficient mechanism to deal with locking shared data structures.
Note that the double-[checked] locking pattern does not work: it is a nice
idea but actually introduces hard to find multi-threading bugs - after all,
you explicitly handle multi-threading. I'm not a multi-threading expert
(unless you count the advice "Avoid using multi-threadings! Use other
approaches, e.g. multi-processing, where viable" as expertise...) to
describe the reasons sufficiently well myself, I have only read arguments
which make sense and reflect my experience with uses of the double-checked
locking pattern. You might want to look at discussions e.g. in
comp.lang.c++.moderated or google for a descriptions of the problems
(<http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html>
may be applicable to some extend).
I'd have to look it up, but I think the map iterators would not be
invalidated, that is an iterator would still "point" to the same element
after an insertion, just that the internal links to its neighbours could
be different, - again, if the rearrangment of the elements is preempted,
imagine what chaos will result if you try to iterate over the
elements...!
On multi-processors choas results even if the rearrangement is not
preempted: the changes are made to the processor's cache and it requires
some form of multi-threading synchronization to make the changes appear
for other processors. Typical processors for multi-processor machines often
have special instructions to flush the cache and invalidate the
corresponding cache sections of other caches. The user interface to these
instructions differ between platforms but a mutex always does the trick.
case 3 - I don't know - cout could be implemented to serialize the two
calls, but might not be for performance reasons with different
implementations.


It is very unlikely that this done: locking internal to a stream is simply
the wrong abstraction level. You need to put locking around the stream. You
might want to preformat the output into a thread-private string stream and
then merely insert the resulting string at once into a thread protected
'std::cout'. This has two positive effects: the output is not garbled and
the time 'std::cout' is blocked is minimized.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting
Jul 22 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Charles Law | last post by:
I have a user control created on the main thread. Let's say, for arguments sake, that it has a single property that maintains a private variable. If I want to set that property from a worker...
4
by: Jonathan Burd | last post by:
Greetings everyone, Here is a random string generator I wrote for an application and I'm wondering about the thread-safety of this function. I was told using static and global variables cause...
1
by: Sanjay Kedare | last post by:
Hi, How safe it is to spawn a thread to do some routine job from Application_Start event of ASP.NET Also whenever the ASPNET worker process restarts, will the Application_Start event be...
17
by: Rainer Queck | last post by:
Hi NG, one more question about thread safety of generic lists. Let's assume a generic list: List<MyTyp> aList = new List<MyType>(); Would it be a problem if one thread removes elements from...
12
by: Vincent RICHOMME | last post by:
Hi, I am currently implementing some basic classes from .NET into modern C++. And I would like to know if someone would know a non mutable string class.
7
by: TS | last post by:
ArrayList myCollection = new ArrayList(); foreach ( Object item in myCollection ) { // code here. } Can someone explain how more than one thread would execute code? So if i have some code in a...
2
by: digz | last post by:
Hi, I am trying to write a program which has two threads one of them write to a map , and the other one deletes entries based on a certain criterion.. first I cannot get the delete portion to...
1
by: paul.hester | last post by:
Hi all, All of the classes in my DAL are static, with constants defining the stored procedures and parameters. I've been having some problems with my site which makes me wonder if there's a...
29
by: NvrBst | last post by:
I've read a bit online seeing that two writes are not safe, which I understand, but would 1 thread push()'ing and 1 thread pop()'ing be thread-safe? Basically my situation is the follows: ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.