Thread safety usage

There is a tutorial JUCE: Tutorial: Looping audio using the AudioSampleBuffer class (advanced)
introducing the usage of the “ScopedTryLockType lock” to keep the thread the safety.

Then I implemented this method and introduced the “using namespace std;” in the same code file.
I got the underneath error after building the code. could anyone give any clues?

error C2228: left of ‘.isLocked’ must have class/struct/union

thanks.

If the name of your ScopedTryLockType instance is lock, and you’ve used using namespace std;, then you’ve got multiple definitions of lock (yours, and std::lock) so the compiler doesn’t know which you intended to use when you say lock.isLocked().

This is exactly why it’s not recommended to use using namespace anything;. But if you really want to, you can just rename your lock variable.

got the idea. really appreciated.

Still have trouble, do you mean to rename the “lock” to another name? it seems do not work.
I put the original code below:

            const juce::SpinLock::ScopedTryLockType *lock* (mutex);


            if (lock.isLocked())
                return currentBuffer;

            return nullptr;

Yeah, you’d need to rename your lock variable to something else to avoid the clash with std::lock.

const juce::SpinLock::ScopedTryLockType spinLock (mutex);

if (spinLock.isLocked())
    return currentBuffer;

return nullptr;

LoopingAudioSampleBufferAdvancedTutorial_02.h (9.2 KB)
The same error after running the build.

I supplement the code file in which I just modify the variable from “lock”->“spinlock” and add the “using namespace std;” based on the tutorial code.

There’s a lot more things in that file called lock. You need to go through all of them and rename them.

Or just remove using namespace std; which would be best practice.

I second what @ImJimmi already suggested, i.e. to remove your using namespace std; directive, as it is only bound to cause more and more clashes in the future, as the standard library is expanded with new classes.

I’ll add to that also the fact that putting it in a .h is especially bad, because that will cause every cpp code that uses that header file to have the std namespace already “imported”, with the potential to cause name clashes also there.

But there is a middle ground between using namespace std at the top of a file and having to type std:: in front of every entity from the standard library: in every scope (i.e. open and closed curly brace) you can for example type using std::vector;, and in that scope you can simply type vector instead of std::vector every time.
This way, you only “import” in each local scope the names that you actually need, avoiding unwanted clashes, and those “imports” are only limited to the area where those names are actually needed, instead of the whole file and the files that #include it.