What is easiest way to create multithreaded applications with C/C++?

前端 未结 15 1564
遥遥无期
遥遥无期 2021-02-06 11:05

What is the easiest way to create multithreaded applications with C/C++?

15条回答
  •  一整个雨季
    2021-02-06 11:18

    It's been a while since I worked in C++ and I haven't seen the Boost threading support, but I found it very helpful to encapsulate semaphore services provided by the OS, usually either POSIX or Win32, in simple classes that would acquire locks, and release them in the destructors, making their use fairly simple.

    void operateOnSharedResource(SharableResource & foo) {
        MutexLock lock(foo.getMutex());
        // do stuff to foo
        // implicit call to MutexLock dtor performs release 
    }
    

    Ultimately there are lots of simple tricks like this to ease thread programming and I'd be surprised if Boost didn't have something like this by now (EDIT: It does and it's documented in Lock Types).

    Regardless, the main problem with writing multi-threaded code isn't going to be solved by any third party library, and that's understanding where your code can be parallelized usefully, and where shared resources are going to be touched and must be accounted for. Here's a few rules of thumb I use when writing multi-threaded code.

    • Try to minimize the number of shared resources
    • Try to encapsulate shared resources in class wrappers that make all operations atomic.
    • Make worker threads as simple as possible

    Proper encapsulation really does wonders for writing safer multi-threaded code, because the fewer things you can see, the fewer things can have a race condition.

提交回复
热议问题