开发者

In a multithreaded app, how would I use the atomic builtins to set/view a time_t value?

I have an app that is highly threaded.

The threads in this app read from a shared memory mapped file. You can assume they never write to it.

Now what I need to do is extend it so that when a reader has finished reading from the file, it will update a shared timestamp. i.e. time_t last_access_time = time(NULL);

That happens so often, that I would prefer to search for a lock-free implementation if at all possible.

How would I go about setting or checking the current value of last_acces开发者_如何学Gos_time using the atomic builtins in G++?

e.g. suppose I have these class members and _last_access_time is initialised to time(NULL)

time_t _last_access_time;

void UpdateLastAccessTime(){
     _last_access_time = time(NULL);
}

void GetLastAccessTime(){
     return _last_access_time;
}

Is it possible to make it lock free?


class SomeClass
{
public:
    inline
    SomeClass ()
        : m_lastAccessTime (0)
    { ; }

    inline void
    UpdateLastAccessTime ()
    {
        time_t crtTime = time (NULL);
        time_t lastTime = m_lastAccessTime;

        while (crtTime > lastTime)
        {
            lastTime = __sync_val_compare_and_swap (
                &m_lastAccessTime,
                lastTime,
                crtTime);
        }
    }

    inline time_t
    GetLastAccessTime () const
    {
         return m_lastAccessTime;
    }

private:
    volatile time_t m_lastAccessTime;
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜