Link to home
Start Free TrialLog in
Avatar of ITSpgrmr
ITSpgrmr

asked on

InterlockedExchange for string

When write to variables that are used in multiple threads, I read that I need to use InterlockedExchange() to lock the variable.  This function works great for integers but I have a variable that is a string.  Is there a function to do the same thing for strings.
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Oh, and when you no longer need the CRITICAL_SECTION, clean up using

DeleteCriticalSection(&g_cs);
a nicer way would be to encapsulate the whole CRITICAL_SECTION stuff in a RAII object like:

class Lock
{
    public:
        Lock() {InitializeCriticalSection(&lock_);}
        ~Lock() {DeleteCriticalSection(&lock_);}

        void lock () const
        {
            EnterCriticalSection (&lock_);
        }

     bool unlock () const
        {
            LeaveCriticalSection (&lock_);
            return true;
        }

    private:
        mutable CRITICAL_SECTION lock_;

        // no copy and assignment
        Lock (const Lock &src);
        Lock& operator= (const Lock &src);
};
sorry

       bool unlock () const
        {
            LeaveCriticalSection (&lock_);
            return true;
        }

should be

       void unlock () const
        {
            LeaveCriticalSection (&lock_);
        }

regards
than all you need is a other class like

class Locker
{
    public:
        explicit Locker (Lock &lock) : lock_(lock)  {lock_.lock();}
        ~Locker() {lock_.unlock();}

    private:
        Lock& lock_;

        // no copy and assignment
        Locker (const Locker &src);
        Locker& operator= (const Locker &src);
};


so you could use is it like

....

Lock lock;
lock.lock();

your string code...

lock.unlock;

or as RAII

Lock lock; // as member of an object or in function....

Locker lockthis(lock);
your string code...

// the lock will be release as soon as lockthis will be out of scope

regards

Even though a wrapper class is nice, I'd rather start out with the basics when learning a new API. Just my 2 Cents here, though.