简体   繁体   中英

Why do different threads not execute in order?

hi i am writing a test for pthreads and i am wondering if anyone could tell me when i execute the following program

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *myfunc (void *myvar);



int main(int argc, char *argv[])
{


  pthread_t thread1, thread2, thread3;

  char *msg1 = "First thread";
  char *msg2 = "Second Thread";
  char *msg3 = "Third thread";

  int ret1, ret2, ret3;


  ret1 = pthread_create(&thread1, NULL, myfunc, (void *) msg1);
  ret2 = pthread_create(&thread2, NULL, myfunc, (void *) msg2);
  ret3 = pthread_create(&thread3, NULL, myfunc, (void *) msg3);


  printf("Main func after pthread_create\n");

  pthread_join(thread1, NULL);
  pthread_join(thread2, NULL);
  pthread_join(thread3, NULL);


  printf("Frist thread ret1 = %d\n", ret1);
  printf("Second thread ret2 = %d\n", ret2);
  printf("Third thread re3 = %d\n", ret3);
}


void *myfunc(void *myvar){

  char *msg;
  msg = (char *)myvar;

  int i;
  for( i =0; i < 10; i++){
    printf("%s %d\n", msg, i);
    sleep(1);
  }

  return NULL;

}

console output:

First thread 0
Second Thread 0
Third thread 0
Main func after pthread_create
Third thread 1
Second Thread 1
First thread 1
Third thread 2
First thread 2
Second Thread 2
Third thread 3
First thread 3
Second Thread 3
Third thread 4
First thread 4
Second Thread 4
First thread 5
Second Thread 5
Third thread 5
First thread 6
Second Thread 6
Third thread 6
First thread 7
Second Thread 7
Third thread 7
First thread 8
Second Thread 8
Third thread 8
Second Thread 9
First thread 9
Third thread 9
Frist thread ret1 = 0
Second thread ret2 = 0
Third thread re3 = 0

Why the threads aren't always executed in order ie (First thread then Second Thread then Third Thread?

Thanks

Properties of threads:

Threads are flows of control within the SAME program

As such, all threads share the same memory space !!!

All threads share all global variables in the program

Threads do not share their local variables (unless they convey the location (address) of their variable to other threads)

Threads can be ready to run or blocked.


Threads that are ready to run will be executed in no particular order by the computer system (the programmer does not have (nor need) control over the therad scheduling --- you could do some thead scheduling, but it is not worth the effort


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM