2011-02-14 34 views
3

我开始在linux上做pthread编程,并且在第一个程序中我完全搞不懂。下面是我正在运行的程序linux上的pthread执行

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

void *print_message_function(void *ptr); 

int main(){ 
pthread_t thread1, thread2; 
char *message1 = "Thread 1"; 
char *message2 = "Thread 2"; 
int iret1, iret2; 

/* Create independent threads each of which will execute function */ 

iret1 = pthread_create(&thread1, NULL, print_message_function, (void*) message1); 
iret2 = pthread_create(&thread2, NULL, print_message_function, (void*) message2); 

/* Wait till threads are complete before main continues. Unless we */ 
/* wait we run the risk of executing an exit which will terminate */ 
/* the process and all threads before the threads have completed. */ 

pthread_join(thread1, NULL); 
printf("amit"); 
pthread_join(thread2, NULL); 

printf("Thread 1 returns: %d\n",iret1); 
printf("Thread 2 returns: %d\n",iret2); 
exit(0); 
} 

void *print_message_function(void *ptr){ 
char *message; 
message = (char *) ptr; 
printf("%s \n", message); 
} 

我想知道的第一件事是线程执行的顺序是不连续的?

第二件事是我intelectally把印刷(“阿米特”);看到main在thread1终止时真的停止了,但是在输出中我们可以看到的是printf语句首先被执行。整个过程的输出是

线程1

线程2

amitThread 1返回:0

线程2返回:0

+6

”是线程执行顺序不是顺序的“。这是正确的。如果你发现这里有足够的惊喜,请离开代码并找到一本书的多线程编程。请一路阅读本书。在编写更多或更少的随机代码之前,您可能会寻找一个好的教程。这个问题相当复杂,而不是偶然探索的东西。 https://computing.llnl.gov/tutorials/pthreads/ – 2011-02-14 11:15:50

+0

这真的是输出?它输出`ajay`而不是`amit`?你有什么问题? – Falmarri 2011-02-14 11:16:37

+0

对不起amit不ajay – 2011-02-14 11:17:30

回答

2

首先有一两件事我想知道线程执行的顺序是不是顺序的?

不正常。大多数现代操作系统上的线程(Linux上的早期线程实现使用协作式多任务)并行执行,并且您的执行顺序部分不确定。该pthread_join小号强加某种排序的事情,所以:因为主线程等待线程1打印Amit1

  • Thread 2一定要来,因为第二pthread_joinThread 1 returns:之前之前完成

    • Thread 1必须Amit面前。 main中的所有printf均按照出现在main中的顺序显示。

    我希望能回答你的问题。我不完全确定你在问什么,但可以随时要求澄清任何问题。

  • 11

    你说得对,线程执行顺序不是连续的。在某种程度上,这就是使用线程的全部要点,即同时运行其他任务。

    您看到的输出与预期的一样,可能会有所不同。

    或许这将帮助:

    main   thread1  thread2 
        |     
        |--create--------+-----------\ 
        |    |   | 
        |   "Thread 1"  | "Thread 2" can 
        |    |   |<- occur anywhere 
        |    /   | along this line 
        join(1) ---------    | 
        |       | 
        |       | 
        "amit"       | 
        |       | 
        |       | 
        join(2) ---------------------/ 
        | 
        | 
    "Thread 1 returns" 
    "Thread 2 returns" 
        | 
        exit(0) 
    

    你拥有的唯一的保证是:

    • Thread 1” 将永远是前 “amit”(打印,因为pthread_join()等待线程1结束前主程序可以继续)
    • Thread X returns ...”语句总是在两个线程终止后结束。 “