Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As <a href="https://stackoverflow.com/a/14402485/12711">Useless mentioned in his answer</a>, strictly speaking the thread function called by the <code>pthread</code> library needs to be <code>extern "C"</code>. While a static member function works in nearly all cases, from a language lawyer point of view and at least one real life situation, it's not correct. See <a href="https://stackoverflow.com/a/2068048/12711">https://stackoverflow.com/a/2068048/12711</a> for details.</p> <p>However, you can have an <code>extern "C"</code> function provide the interface between the <code>pthread</code> library and your class template, but it does seem to require a tiny bit of overhead:</p> <pre><code>#include &lt;pthread.h&gt; struct trampoline_ctx { void* (*trampoline)(void*); void* obj; }; extern "C" void* trampoline_c(void* ctx) { struct trampoline_ctx* t = static_cast&lt;struct trampoline_ctx*&gt;(ctx); return (t-&gt;trampoline)(t-&gt;obj); } template &lt;class T, void * (T::*thread)()&gt; class Thread { public: int create(T *that) { ctx.trampoline = _trampoline; ctx.obj = that; return pthread_create(&amp;_handle, nullptr, trampoline_c, &amp;ctx); }; pthread_t getHandle() const { return _handle; }; private: static void * _trampoline(void *that) { return (static_cast&lt;T *&gt;(that)-&gt;*thread)(); }; pthread_t _handle; struct trampoline_ctx ctx; }; </code></pre> <p>I agree that composition rather than inheritance is probably a better model for threading most of the time.</p> <p>Of course, remember that C++11 provides <code>std::thread</code> which is a templated, non-inheritance design. And see <code>boost::thread</code> if C++11 isn't an option.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload