简体   繁体   中英

Current right way to do thread programming in Linux

I know that the implementation of threads in the Linux kernel and libc went through big changes in the past. What is the best way to use threads today from C programs? (I don't even know if there is more than one API that I can use -- I just know pthreads)

I don't care too much about old kernels and libc versions, but I do care about making efficient use of multiple cores and about portability (I may want my code to also work on other Unixes).

If I just use Posix threads as described in man 7 pthreads and restrict my code to the POSIX API will that be OK?

edit : thanks to all who answerd. I did think of using some available thread pool library, but for this project this really isn't an option.

For the most part, yes. That's the point of POSIX. Each platform you plan to port to (including down to the OS, kernel number, and architecture) may have some differences that you'll need to be aware of. This is your homework :)

Also, as a piece of advice, frameworks like Qt and library packages like Boost make a lot of this work more elegant. If you can integrate them, I highly recommend it.

POSIX threads are a good choice and a popular one. You may also want to look at Boost Threads and Intel Thread Building Blocks for other options when programming in C/C++, rather than coding directly to the POSIX API. Specifically Intel TBB claims to use multi-core processors in an easy to use and efficient manner. I don't have much experience with TBB, but I've seen demos where using TBB reduced code size and complexity dramatically and ran orders-of-magnitude faster than an implementation written in straight C++ using POSIX threads written by an experienced engineer.

Using threads is difficult and error-prone. Avoid programming them directly, if possible. A well-written paper on the subject can be found here .

Multicore parallelism can be achieved in a variety of different ways, other than direct use of threads. The most straightforward is multi-process parallelism. For n cores, run n processes and subdivide the workload among them. This is most appropriate when tasks are coarse-grained and require little or no communication between them. When it has to be in-process, you can use message-passing for all communication and synchronisation between threads and try to always pass immutable objects as messages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM