我有一个在LINUX中创建进程线程的C ++程序。如何修改此代码以创建无限量的进程?我的计数目前设为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);
}
答案 0 :(得分:0)
对于无限,我建议进行以下更改:
将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);
}