具有c ++中两个线程的多线程程序

时间:2018-05-04 00:43:38

标签: c++ multithreading operating-system system

我有一个多线程程序,我们正在系统工程类中查看。 该计划如下。

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

// repeat the times (*) operation 100,000 times to slow down the
// execution of the instructions
#define RPT 100000

void* print_X() {
   int i;
   float x;
   while (1) {
   // the multiplication operation below is for consuming some CPU       
   //time to slow down the execution

   for(i=0; i<RPT; i++) { 
   x = 3.1415926*3.1415926; 
}
   printf("X"); 
   }
 } 


void* print_O() {
   int i;float x;

   while (1) {
   // the multiplication operation below is for consuming some CPU       
   //time to slow down the execution

  for(i=0; i<RPT; i++) { 
     x = 3.1415926*3.1415926; 
   }

   printf("O"); 
    }
   } 

int main () {
   pthread_t tid1, tid2;pthread_create (&tid1, NULL, &print_X, NULL);
   pthread_create (&tid2, NULL, &print_O, NULL);
  // Wait till threads complete. Not really related to this
  // question in this assignment. Can be ignored.pthread_join(tid1, NULL);pthread_join(tid2, NULL);


 printf ("\n==========================\n");

 }

所以基本上这个程序运行1000次以减慢执行速度,两个进程相互竞争以产生下面的输出。 (输出有行号和新行只是为了使它更具可读性。)

01:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
02:OOOOOOOOOOOOOO 03:XXXXXXXXXXXXXXXXXXX
04:OOOOOOOOOOOOOOOOOOO 05:XXXXXXXXXXXXXXXXXX
06:OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO 07:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
08:XXX
09:O
10:X
11:O
12:X
13:O
14:X
15:O
16:XXXXXXXXXXXXXXXXXXXXXXXXX
17:000OOOOOOOOOOOOOO000OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO 18:XXXXXXXXXXXXXXXXXXXXXXX
19:000OOOOOOOOOOOOOOOO0000OOO

我唯一的问题还涉及第08到第15行。我们被问到这个输出的可能原因是什么(基本上是一个一个),我无法理解每个线程会停止并让位于另一个线程会发生什么这样连续7次? 教科书涉及互斥,僵局和饥饿等概念,但我对这一主题的知识水平无法理解这种情况会如何发生?

非常感谢任何帮助。

0 个答案:

没有答案
相关问题