PageRenderTime 476ms CodeModel.GetById 214ms app.highlight 16ms RepoModel.GetById 161ms app.codeStats 1ms

/mordor/thread.h

http://github.com/mozy/mordor
C Header | 96 lines | 63 code | 17 blank | 16 comment | 0 complexity | ba20641aebda37127fc48cc66a4155ab MD5 | raw file
 1#ifndef __MORDOR_THREAD_H__
 2#define __MORDOR_THREAD_H__
 3// Copyright (c) 2010 - Mozy, Inc.
 4
 5#include <iosfwd>
 6
 7#include <boost/function.hpp>
 8#include <boost/noncopyable.hpp>
 9
10#include "version.h"
11#ifndef WINDOWS
12#include "semaphore.h"
13#endif
14
15namespace Mordor {
16
17#ifdef WINDOWS
18typedef DWORD tid_t;
19#elif defined(LINUX)
20typedef pid_t tid_t;
21#elif defined(OSX)
22typedef mach_port_t tid_t;
23#else
24typedef pthread_t tid_t;
25#endif
26
27inline tid_t emptytid() { return (tid_t)-1; }
28tid_t gettid();
29
30class Scheduler;
31
32class Thread : boost::noncopyable
33{
34public:
35    /// thread bookmark
36    ///
37    /// bookmark current thread id and scheduler, allow to switch back to
38    /// the same thread id later.
39    /// @pre The process must be running with available scheduler, otherwise
40    /// it is not possible to switch execution between threads with bookmark.
41    /// @note Bookmark was designed to address the issue where we failed to
42    /// rethrow an exception in catch block, because GCC C++ runtime saves the
43    /// exception stack in a pthread TLS variable. and swapcontext(3) does not
44    /// take care of TLS. but developer needs to be more aware of underlying
45    /// thread using thread bookmark, so we developed another way to fix this
46    /// problem. thus bookmark only serve as a way which allow user to stick
47    /// to a native thread.
48    class Bookmark
49    {
50    public:
51        Bookmark();
52        /// switch to bookmark's tid
53        void switchTo();
54        /// bookmark's tid
55        tid_t tid() const { return m_tid; }
56
57    private:
58        Scheduler *m_scheduler;
59        tid_t m_tid;
60    };
61
62public:
63    Thread(boost::function<void ()> dg, const char *name = NULL);
64    ~Thread();
65
66    tid_t tid() const { return m_tid; }
67
68    void join();
69
70private:
71    static
72#ifdef WINDOWS
73    unsigned WINAPI
74#else
75    void *
76#endif
77    run(void *arg);
78
79private:
80    tid_t m_tid;
81#ifdef WINDOWS
82    HANDLE m_hThread;
83#else
84    pthread_t m_thread;
85#endif
86
87#ifdef LINUX
88    boost::function<void ()> m_dg;
89    Semaphore m_semaphore;
90    const char *m_name;
91#endif
92};
93
94}
95
96#endif