hi, 

so i currently have a hands on pthread, playing around and do some testing. 
while most behavior is expected by me, there are some are not. 
im not quite understand how threads work especially when then can cut other 
thread from the processor. 

so i have a very simple program that creates 5 threads, each thread only prints 
a line of sentence. So here is the sniplet from the main code:

for (t = 0; t<NUM_THREADS; t++) {
  std::cout << "in main creating thread " << t << std::endl;
  rc = pthread_create(&threads[t], NULL, printHello, (void*)t);
  if(rc) {
        std::cout << "ERROR: return code from pthread_create()" << rc;
        std::cout << std::endl;
        exit(1);
  }
}

and each thread will do printHello routine/function like this:

void *printHello(void *threadId) {
  long tid;
  tid = (long)threadId;
  std::cout << "Hello world! its me thread " << tid << std::endl;
  pthread_exit(NULL);
}


The expected(and most happen) result is like this: 

in main creating thread 0
in main creating thread 1
in main creating thread 2
in main creating thread 3
Hello world! its me thread 0
Hello world! its me thread 1
Hello world! its me thread 2
in main creating thread 4
Hello world! its me thread 3
Hello world! its me thread 4

and order does not matter. 
However i also notice this result:

in main creating thread Hello world! its me thread 32

which means that the thread was cut before finishing one line of command. 

Is there any way to set the thread not to cut other thread while doing one 
single command? are there a way to tell other thread "DONT CUT ME WHILE DOING 
THIS/FROM THIS LINE TO THAT LINE!" in a line(s) of code?


thanks in advance :)

================================= 
http://www.svnstrk.blogspot.com  
=================================


      

Reply via email to