Re: thread safety of C++ standard library
Re: thread safety of C++ standard library
- Subject: Re: thread safety of C++ standard library
- From: Clark Cox <email@hidden>
- Date: Wed, 2 Dec 2009 21:08:57 -0800
On Tue, Dec 1, 2009 at 3:15 PM, Jonathan Prescott
<email@hidden> wrote:
> std::sort is a template function defined in /usr/include/c++/(4.0.1,4.2.1)/bits/stl_algo.h. If you look at the code, you'll see that it's not thread-safe,
How did you come to that conclusion? Where does std::sort access any
shared state? As long as the sequence being sorted and the comparator
aren't itself being accessed from other threads std::sort is fine to
use.
> and it's actually platform-independent (I first saw these routines on SGI stuff way back when). They've been updated by the gcc folks to add in some gcc-specific conventions, but, the algorithms themselves are almost direct from SGI IRIX.
>
> However, that may be all right. First thing you need to decide is what are you worried about when you are concerned about thread safety? I'm assuming that your concern is that 1) the collections you want to sort are global thread variables, and 2) that being the case, you don't want the collections being sorted to be changed underneath you while you are sorting. If that is the case, you will need to read-lock both collections using pthread mutexes or some other synchronization technique before sorting. If the iterators are declared as local to the thread doing the sorting, like:
>
> std::vector<int> collect1;
> std::vector<int>::iterator itor1=collect1.begin();
> std::list<double> collect2;
> std::list<double> itor2=collect2.begin();
>
> std::sort(itor1, itor2, IntToRealLT);
That is not legal code. It is not legal to pass iterators into
unrelated collections to sort, nor are vector and list iterators
compatible.
--
Clark S. Cox III
email@hidden
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden