为什么不同的线程不按顺序执行?

时间:2015-05-12 16:50:22

标签: c multithreading pthreads

嗨我正在为pthreads编写测试,我想知道是否有人能告诉我何时执行以下程序

#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;

}

控制台输出:

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

为什么线程并不总是按顺序执行,即(第一个线程然后是第二个线程然后是第三个线程?

由于

1 个答案:

答案 0 :(得分:1)

线程属性:

线程是SAME程序中的控制流

因此,所有线程共享相同的内存空间!!!

所有线程共享程序中的所有全局变量

线程不共享它们的局部变量(除非它们将变量的位置(地址)传递给其他线程)

线程可以准备好运行或阻止。

  

准备运行的线程将不按特定顺序执行   由计算机系统(程序员没有(也不需要)   控制therad调度 - 你可以做一些thead   调度,但不值得努力