Advertisement
BaSs_HaXoR

C++ Multi-Threading Tutorial

Mar 2nd, 2015
741
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. /*
  2.  
  3. How to multi-thread in C++:
  4.  
  5. Multithreading is a specialized form of multitasking and a multitasking is the feature that allows your computer to run two or more programs concurrently. In general, there are two types of multitasking: process-based and thread-based.
  6.  
  7. Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the same program.
  8.  
  9. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.
  10.  
  11. C++ does not contain any built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature.
  12.  
  13. This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C++ program using POSIX. POSIX Threads, or Pthreads provides API which are available on many Unix-like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X and Solaris.
  14.  
  15. */
  16.  
  17. #include <iostream>
  18. #include <cstdlib>
  19. #include <pthread.h>
  20.  
  21. using namespace std;
  22.  
  23. #define NUM_THREADS     5
  24.  
  25. void *PrintHello(void *threadid)
  26. {
  27.    long tid;
  28.    tid = (long)threadid;
  29.    cout << "Hello World! Thread ID, " << tid << endl;
  30.    pthread_exit(NULL);
  31. }
  32.  
  33. int main ()
  34. {
  35.    pthread_t threads[NUM_THREADS];
  36.    int rc;
  37.    int i;
  38.    for( i=0; i < NUM_THREADS; i++ ){
  39.       cout << "main() : creating thread, " << i << endl;
  40.       rc = pthread_create(&threads[i], NULL,
  41.                           PrintHello, (void *)i);
  42.       if (rc){
  43.          cout << "Error:unable to create thread," << rc << endl;
  44.          exit(-1);
  45.       }
  46.    }
  47.    pthread_exit(NULL);
  48. }
  49.  
  50. //Source: http://www.tutorialspoint.com/cplusplus/cpp_multithreading.htm
  51. //BaSs_HaXoR
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement