Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreading in C++ ... where to start?

I'd like to start learning multithreading in C++. I'm learning it in Java as well. In Java, if I write a program which uses multithreading, it will work anywhere. However in C++, doesn't multithreading rely on platform-specific API's? If so, that would seem to get in the way of portability.

How can I do multithreading in C++ without causing portability issues? Is boost's thread library a good solution?

As a sidenote - how is it even possible to implement multithreading as a library? Isn't that something that has to be done by the compiler?

like image 480
Cam Avatar asked Jun 26 '10 17:06

Cam


People also ask

Can you do multithreading in C?

Can we write multithreading programs in C? Unlike Java, multithreading is not supported by the language standard. POSIX Threads (or Pthreads) is a POSIX standard for threads. Implementation of pthread is available with gcc compiler.

How do I run a thread program?

To execute the c file, we have to use the -pthread or -lpthread in the command line while compiling the file. Syntax: int pthread_create(pthread_t * thread, const pthread_attr_t * attr, void * (*start_routine)(void *), void *arg);

Is C single threaded or multi threaded?

C is a language that runs on one thread by default, which means that the code will only run one instruction at a time.

Can we start multiple threads?

If our computer has a multi-core CPU or multiple CPUs, two threads can possibly start at the exact same time. However, we cannot control it on the Java side. This is because when we work with threads in Java, the Java thread scheduling depends on the thread scheduling of the operating system.


1 Answers

If you do not have a compiler that supports C++0x yet (available with visual studio c++ 2010 for example), use boost threads. (Unless you use a framework that already supports threading, which is not the case - you wouldn't ask the question otherwise -). These boost threads became actually the standard in the brand new C++. Before that time C++ itself was thread unaware.

TBB Threading Building Blocks might also be interesting to you if you want to learn other aspects in parallel programming.

Regarding Qt: if you only want threading support it is complete overkill. It has horribly slow round trip times from compiling to result. It is really well designed thought. But not an official standard like the C++0x threads from boost. Therefore I would not take it as a first choice.

like image 91
jdehaan Avatar answered Oct 01 '22 23:10

jdehaan