gpt4 book ai didi

c++ - 编写并执行创建无限数量进程的 C 或 C++ 程序。

转载 作者:太空宇宙 更新时间:2023-11-04 05:51:16 25 4
gpt4 key购买 nike

我有一个 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);

}

最佳答案

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

for 循环替换为 while (true)

替换:

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);
}

关于c++ - 编写并执行创建无限数量进程的 C 或 C++ 程序。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36654049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com