编写并执行一个C或C++程序,该程序可创建无限数量的进程

Write and execute a C or C++ program that creates an infinite number of processes.

本文关键字:程序 创建 无限 进程 C++ 执行 一个      更新时间:2023-10-16

我有一个C++程序,它在LINUX中创建进程线程。如何修改此代码以创建无限数量的进程?我的计数当前设置为5。这是我的代码:

#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <stdint.h>
#include <inttypes.h>
using namespace std;
#define THREAD_COUNT     5
void *PrintPhrase(void *threadid)
{
   long tid;
   tid = (long)threadid;
   cout << "THis Is A Great Day Thread ID, " << tid << endl;
   pthread_exit(NULL);
}
int main ()
{
   pthread_t threads[THREAD_COUNT];
   int rc;
   uintptr_t i;
   for( i=0; i < THREAD_COUNT; i++ ){
      cout << "main() : creating thread, " << i << endl;
      rc = pthread_create(&threads[i], NULL, 
                          PrintPhrase, (void *)i);
      if (rc){
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }
  pthread_exit(NULL);
}

对于无限,我建议进行以下更改:

while (true)替换for循环。

替换:

pthread_t threads[THREAD_COUNT];

带有:

std::vector<pthread_t> threads;

你的循环看起来像:

   while (true)
   {
      pthread temp;
      rc = pthread_create(&temp, NULL, 
                          PrintPhrase, (void *)i);
      if (rc){
         cout << "Error:unable to create thread," << rc << endl;
         return EXIT_FAILURE;
      }
      threads.push_back(temp);
   }