fork(1) download
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <pthread.h>
  4.  
  5. using namespace std;
  6.  
  7. #define NUM_THREADS 2
  8.  
  9. int arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  10.  
  11. void *splitLoop(void *threadid)
  12. {
  13. long tid;
  14. tid = (long)threadid;
  15. //cout << "Hello World! Thread ID, " << tid << endl;
  16. int start = (tid * 5);
  17. int end = start + 5;
  18. for(int i = start;i < end;i++){
  19. cout << arr[i] << " ";
  20. }
  21. cout << endl;
  22. pthread_exit(NULL);
  23. }
  24.  
  25. int main ()
  26. {
  27. pthread_t threads[NUM_THREADS];
  28. int rc;
  29. int i;
  30. for( i=0; i < NUM_THREADS; i++ ){
  31. cout << "main() : creating thread, " << i << endl;
  32. rc = pthread_create(&threads[i], NULL,
  33. splitLoop, (void *)i);
  34. if (rc){
  35. cout << "Error:unable to create thread," << rc << endl;
  36. exit(-1);
  37. }
  38. }
  39. pthread_exit(NULL);
  40. }
Success #stdin #stdout 0s 19848KB
stdin
Standard input is empty
stdout
main() : creating thread, 0
main() : creating thread, 1
5 6 7 8 9 
0 1 2 3 4