2016-05-08 4 views
2

私は、学校プロジェクトのいくつかの数値にいくつかの数学を行うプログラムを作っていました。私は10個のスレッドを持っているが、42個のアイテムが処理されているとすれば、それらがすべてのアイテムを均等に処理し、均等な量のジョブを取るようにしたい。私はPOSIXのpthreadライブラリを使っていますが、それはmutexと何か関係がありますが、私は完全にはわかりません。スレッド間の処理を分割しますか? (pthread)

ここでは私がやっていることの単純化した例がありますが、仕事の負荷を均等に均衡させたいと思います。

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

int numbers = { 1, 78, 19, 49, 14, 1, 14. 19, 57, 15, 95, 19, 591, 591 }; 

void* method() { 
    for(size_t i = 0; i < 14; i++) { 
    printf("%d\n", (numbers[i] * 2)); 
    } 
} 

int main(int argc, char const *argv[]) { 
    pthread_t th[10]; 
    for (size_t i = 0; i < 10; i++) { 
    pthread_create(&th[i], NULL, method, NULL); 
    } 
    return 0; 
} 
+0

これは、プロセスのタイプと処理する必要のある_items_によっても異なる場合があります。いずれにしても、スレッド引数 - 引数#4を 'pthread_create()'に適切に作成し、アイテムへのポインタを渡すようにしてください。 – user3078414

答えて

1

テーブル内の指定されたインデックスを各スレッドで処理する必要があります。同じデータに対して競合しないように、スレッド間で作業を適切に分割する限り、ミューテックスでテーブルを保護する必要はありません。

アイデア:もう少し複雑な例については

/* this structure will wrap all thread's data */ 
struct work 
{ 
    size_t start, end; 
    pthread_t  tid; 
}; 

void* method(void*); 
#define IDX_N 42 /* in this example */ 
int main(int argc, char const *argv[]) 
{ 
    struct work w[10]; 
    size_t idx_start, idx_end, idx_n = IDX_N/10; 
    idx_start = 0; 
    idx_end = idx_start + idx_n; 
    for (size_t i = 0; i < 10; i++) 
    { 
    w[i].start = idx_start; /* starting index */ 
    w[i].end = idx_end; /* ending index */ 
    /* pass the information about starting and ending point for each 
    * thread by pointing it's argument to appropriate work struct */ 
    pthread_create(&w[i], NULL, method, (void*)&work[i]); 
    idx_start = idx_end; 
    idx_end = (idx_end + idx_n < IDX_N ? idx_end + idx_n : IDX_N); 
    } 
    return 0; 
} 
void* 
method(void* arg) 
{ 
    struct work *w = (struct work* arg); 
    /* now each thread can learn where it should start and stop 
    * by examining indices that were passed to it in argument */ 
    for(size_t i = w->start; i < w->end; i++) 
    printf("%d\n", (numbers[i] * 2)); 
    return NULL; 
} 

あなたはthisthisを確認することができます。

+0

これらのインデックスを取得するのはどうですか? :S – JustLloyd

+0

手動で実行することも、パーティション分割ロジックを書き込むこともできます。 – 4pie0

+0

@JustLloydロジックを追加 – 4pie0

1

処理する必要があるアイテムの数が事前に分かっている場合は、スレッド間でパーティションを分割するだけで済みます。たとえば、最初のスレッドにアイテム0-9を処理するか、次のプロセス10-19に処理するかなどを伝えます。

関連する問題