2016-04-15 13 views
-2

私はLINUXでプロセススレッドを作成するC++プログラムを持っています。無限の量のプロセスを作成するためにこのコードを変更するにはどうすればよいですか?無限のプロセスを作成するCまたはC++プログラムを作成して実行します。

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

} 
+1

[ 'fork'](http://man7.org/linux/ man-pages/man2/fork.2.html)? – NathanOliver

+0

スレッドはプロセスではなく、大きな違いがあります。 –

+2

[フォーク爆弾](https://en.wikipedia.org/wiki/Fork_bomb)を作成しますか?それはあなたのマシンをとても激しくクラッシュさせるでしょう。あなたが自分でもっと大きな数字に変更することができない場合は、私たちが何を手助けすることができるか分かりません。 – tadman

答えて

0

無限のために、私はこれらの変更を提案:

while (true)forループを交換し、私は、カウント現在、ここに私のコードです。5. に設定されています。

置き換えます

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