Help with pThreads

I am on a mac using terminal and atom and I am following along on [this](http://www.tutorialspoint.com/cplusplus/cpp_multithreading.htm) tutorial on pThreads for my c++ application. When I run the exact command prompt into terminal( gcc test.cpp -lpthread), I get tons of lines of text and then this :
symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

If instead I type: g++ test.cpp -lpthread, then I get no errors, but I get a very broken piece of text seen here:

main() : creating thread, 0
main() : creating thread, 1
HelmlHaoei lnWl(oo)r  lW:do !rc lrTdeh!ar teTiahndrg e IatDdh, r IeD0a,
d ,1 
2
main() : creating thread, 3
main() : creating thread, 4
Hello World! Thread ID, 2
Hello World! Thread ID, 3
Hello World! Thread ID, 4


What should I do? I have no idea what I'm doing wrong.

code:
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
#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

#define NUM_THREADS     5

void *PrintHello(void *threadid)
{
   long tid;
   tid = (long)threadid;
   cout << "Hello World! Thread ID, " << tid << endl;
   pthread_exit(NULL);
}

int main ()
{
   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 (rc){
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
}
Last edited on
Multiple threads are trying to print to the console at the same time. That's why it's mixed up. This is expected.
Last edited on
What should I do?
You need all the output for a line to be done in one function, then place a mutex at the top of that function so only one thread at a time can execute it.
Topic archived. No new replies allowed.