Multi-threading
- Multithreading is a specialized form of multitasking and multitasking is a feature that allows your system to execute two or more programs concurrently. In general, there are two sorts of multitasking: process-based and thread-based.
- Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the multiprogramming of pieces of an equivalent program.
- A multithreaded program contains two or more parts that will run concurrently. Each part of such a program is named a thread, and every thread defines a separate path of execution.
- C++ doesn’t contain any built-in support for multithreaded applications. Instead, it relies entirely upon the OS to supply this feature.
Example:
C++
// C++ Program to implement // the working of Multi-threading #include <cstdlib> #include <iostream> #include <pthread.h> using namespace std; #define NUM_THREADS 5 // Function to print Hello with // the thread id void * PrintHello( void * threadid) { // Thread ID long tid; tid = ( long )threadid; // Print the thread ID cout << "Hello World! Thread ID, " << tid << endl; pthread_exit(NULL); } // Driver Code int main() { // Create thread pthread_t threads[NUM_THREADS]; int rc; int i; for (i = 0; i < NUM_THREADS; i++) { cout << "main() : creating thread, " << i << endl; rc = pthread_create(&threads[i], NULL, PrintHello, ( void *)&i); // If thread is not created if (rc) { cout << "Error:unable to" << " create thread, " << rc << endl; exit (-1); } } pthread_exit(NULL); } |
Output:
This tutorial assumes that you are working on Linux OS and we are going to write a multi-threaded C++ program using POSIX. POSIX Threads or Pthreads provide API which is available on many Unix-like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X, and Solaris.
Features of C++
C++ is a general-purpose programming language that was developed as an enhancement of the C language to include an object-oriented paradigm. It is an imperative and compiled language. C++ has a number of features, including:
- Object-Oriented Programming
- Machine Independent
- Simple
- High-Level Language
- Popular
- Case-sensitive
- Compiler Based
- Dynamic Memory Allocation
- Memory Management
- Multi-threading