Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing C++11 std::thread and C system threads (ie pthreads)

I am writing a multithreaded C++ program and wish to use a multithreaded C library.
This library expects me to use the native system methods to create it some worker threads and pass control to its run() function using code such as this:

void system_specific_thread_init();
#ifdef _WIN32
    DWORD WINAPI system_specific_thread_run( LPVOID unused )
    {
        library_run();
        return 0;
    }

    void system_specific_thread_init()
    {
        Createthread(NULL, 0, system_specific_thread_run, NULL, 0, NULL);
    }
#else
    void* system_specific_thread_run(void *unused)
    {
        library_run();
        return NULL;
    }

    void system_specific_thread_init()
    {
        pthread_t id;
        pthread_create(&id, NULL, system_specific_thread_run, NULL);
    }
#endif
system_specific_thread_init();

after which it will use the relevant native system mutex methods to other native system threads to call its functions while getting on with is own work.

However, I am using the C++11 <thread> library to create and manage all my threads. I wish to create the worker thread(s) with std::thread(library_run) and call the library functions from other such threads.

Is it safe to do this, or will the DS9K cause demons to fly out of my nose?

like image 333
Lex R Avatar asked Sep 18 '12 19:09

Lex R


People also ask

Does std :: thread use pthreads?

The std::thread library is implemented on top of pthreads in an environment supporting pthreads (for example: libstdc++).

Can you use pthreads in C++?

In a Unix/Linux operating system, the C/C++ languages provide the POSIX thread(pthread) standard API(Application program Interface) for all thread related functions. It allows us to create multiple threads for concurrent process flow.

Is pthreads faster than OpenMP?

The results shows that OpenMP does perform better than Pthreads in Matrix Multiplication and Mandelbrot set calculation but not on Quick Sort because OpenMP has problem with recursion and Pthreads does not.

Are pthreads still used?

Yes, the pthreads library is still used for threading. There are some higher level libraries (boost, or if you have a c++ 11 compliant compiler, the standard library) that will also give you threading capabilities, although for somethings you will still need to fall back to the plain pthread call.


1 Answers

C++11 threads may or may not have a member function named native_handle(); it's implementation-defined whether this exists. If it exists, it returns an object of type native_handle_type; it's implementation-defined what an object of this type can be used for. So read your documentation.

like image 190
Pete Becker Avatar answered Oct 05 '22 16:10

Pete Becker