简体   繁体   English

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

[英]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 嗨,我正在为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;

} }

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 线程是SAME程序中的控制流

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 准备运行的线程将由计算机系统以不特定的顺序执行(程序员无需(也不需要)控制therad调度---您可以执行一些thead调度,但是这样做不值得


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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