C++ || Snippet – How To Create And Use Threads For Interprocess Communication
The following is sample code which demonstrates the use of POSIX threads (pthreads), aswell as the pthread_create, and pthread_join function calls on Unix based systems.
Much like the fork() function call which is used to create new processes, threads are similar in that they too are used for interprocess communication. Threads allow for multi-threading, which is a widespread programming and execution model that allows for multiple threads to exist within the same context of a single program.
Threads share the calling parent process’ resources. Each process has it’s own address space, but the threads within the same process share that address space. Threads also share any other resources within that process. This means that it’s very easy to share data amongst threads, but it’s also easy for the threads to step on each other, which can lead to bad things.
The example on this page demonstrates the use of multiple pthreads to display shared data (an integer variable) to the screen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
// ============================================================================ // Author: Kenneth Perkins // Date: Oct 3, 2013 // Taken From: http://programmingnotes.org/ // File: Pthread.cpp // Description: Demonstrate the use of using multiple threads using the // pthread_create() function // ============================================================================ #include <iostream> #include <cstdlib> #include <pthread.h> using namespace std; // Compile & Run // g++ Pthread.cpp -lpthread -o Pthread // ./Pthread <NUMBER OF THREADS TO CREATE> // function prototype void* ThreadFunc(void* args); // global variable int threadNum = 0; int main(int argc, char* argv[]) { // declare variables int numberOfThreads = 0; pthread_t* threads; // make sure theres enough commandline arguments // and EXIT if theres not if(argc < 2) { cout <<"** ERROR - NOT ENOUGH ARGS!\n" <<"\nUSAGE:"<<argv[0]<<" <NUMBER OF THREADS TO CREATE>\n"; exit(1); } // convert the number of threads from the command line // from string to int value numberOfThreads = atoi(argv[1]); // declare the array of thread variables threads = new pthread_t[numberOfThreads]; cout <<"\nThe Parent is creating "<<numberOfThreads<<" threads!" << endl; // use a loop to create the threads for(int x = 0; x < numberOfThreads; ++x) { // create the thread and call the "ThreadFunc" if(pthread_create(&threads[x], NULL, ThreadFunc, NULL) < 0) { perror("pthread_create error"); exit(1); } } cout <<"The Parent is now waiting for the thread(s) to complete...\n\n"; // wait for all threads to finish for(int x = 0; x < numberOfThreads; ++x) { pthread_join(threads[x], NULL); } cout <<"\nAll thread(s) are complete and have terminated!\n" <<"\nThe Parent is now exiting...\n"; return 0; }// end of main /** * The function called by the thread * @param args - pointer to the thread local data */ void* ThreadFunc(void* args) { // display the thread info cout <<"Hi, Im thread #"<<++threadNum <<" and this is my id number: "<<(unsigned)pthread_self()<<endl; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
So, what is the difference between fork() processes and thread processes? Threads differ from traditional multitasking operating system processes in that:
• processes are typically independent, while threads exist as subsets of a process
• processes carry considerable state information, whereas multiple threads within a process share state as well as memory and other resources
• processes have separate address spaces, whereas threads share their address space
• processes interact only through system-provided inter-process communication mechanisms.
• Context switching between threads in the same process is typically faster than context switching between processes.
To use pthreads, the compiler flag “-lpthread” must be set.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
The following is sample output:
./Pthread 5
The Parent is creating 5 threads!
The Parent is now waiting for the thread(s) to complete...Hi, Im thread #1 and this is my id number: 1664468736
Hi, Im thread #2 and this is my id number: 1647683328
Hi, Im thread #3 and this is my id number: 1656076032
Hi, Im thread #4 and this is my id number: 1672861440
Hi, Im thread #5 and this is my id number: 1681254144All thread(s) are complete and have terminated!
The Parent is now exiting...
Leave a Reply