読み取りと書き込みに2つのスレッドを使用するCプログラムを作成しました。両方のスレッドがアクセスする変数をグローバルとして宣言しました。この場合、グローバル変数の使用を回避する方法。
6 に答える
pthread
C で共有グローバル変数に排他的にアクセスするには、Cのライブラリの次のメソッドを調べてください。
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
同様に、C スレッドでグローバル変数の使用を同期するためにセマフォを調べることができます。
共有変数が本当に必要ですか、それともスレッドごとに同じデータの 2 つのコピーが実際に必要ですか? その場合、それをグローバルに宣言する代わりに、作成時に引数としてスレッドに渡します。
本当に共有する必要がある場合は、ミューテックスで保護する必要があります。共有変数をミューテックスとともに構造体にバンドルし、作成時に引数としてスレッドに渡す場合、グローバル変数を廃止することもできます。
この場合、グローバル変数の使用を避ける方法。
グローバル変数を避ける必要はありません。考慮しなければならないのは、何らかのロックメカニズムによる有効なデータだけです。
すべてのグローバル変数を構造体に入れるのは、プロジェクトが大きくなったときの読みやすさとコード制御のためです。
ミューテックス ロックを使用することをお勧めします。これは、変更されたサンプル コードです。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
/* Define globally accessible variables and a mutex */
#define NUMTHRDS 4
#define VECLEN 100
DOTDATA dotstr;
pthread_t callThd[NUMTHRDS];
pthread_mutex_t mutexsum;
void *dotprod(void *arg)
{
/* Define and use local variables for convenience */
int i, start, end, len ;
long offset;
double mysum, *x, *y;
offset = (long)arg;
len = dotstr.veclen;
start = offset*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
/*
Perform the dot product and assign result
to the appropriate variable in the structure.
*/
mysum = 0;
for (i=start; i<end ; i++)
{
mysum += (x[i] * y[i]);
}
/*
Lock a mutex prior to updating the value in the shared
structure, and unlock it upon updating.
*/
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
pthread_mutex_unlock (&mutexsum);
pthread_exit((void*) 0);
}
/*
The main program creates threads which do all the work and then
print out result upon completion. Before creating the threads,
the input data is created. Since all threads update a shared structure,
we need a mutex for mutual exclusion. The main thread needs to wait for
all threads to complete, it waits for each one of the threads. We specify
a thread attribute value that allow the main thread to join with the
threads it creates. Note also that we free up handles when they are
no longer needed.
*/
int main (int argc, char *argv[])
{
long i;
double *a, *b;
void *status;
/* Assign storage and initialize values */
a = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double));
b = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double));
for (i=0; i<VECLEN*NUMTHRDS; i++)
{
a[i]=1.0;
b[i]=a[i];
}
dotstr.veclen = VECLEN;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, NULL);
for(i=0; i<NUMTHRDS; i++)
{
/*
Each thread works on a different set of data.
The offset is specified by 'i'. The size of
the data for each thread is indicated by VECLEN.
*/
pthread_create(&callThd[i], NULL, dotprod, (void *)i);
}
/* Wait on the other threads */
for(i=0; i<NUMTHRDS; i++)
{
pthread_join(callThd[i], &status);
}
/* After joining, print out the results and cleanup */
printf ("Sum = %f \n", dotstr.sum);
free (a);
free (b);
pthread_mutex_destroy(&mutexsum);
pthread_exit(NULL);
}
起動時に作業データを渡すことで、スレッドがグローバルにアクセスするのを避ける方法を尋ねていると思います。
pthread_create の最後のパラメーターを参照してください。これにより、任意のユーザー定義のカスタム ポインターを定義できます。それを使用してデータを渡します (構造体アドレスや値渡しなど、値がプラットフォームの void ポインターのサイズに収まる限り)。
たとえば、親は次のようにして子スレッド データを送信できます。
Data data;
pthread_create(&thrd, NULL, threadProc, &data);
子プロシージャは、次の方法でこれを参照します。
void *threadProc(void *pv)
{
Data *pData = (Data*)pv;
.. use data here...
pthread_exit(NULL);
}
これが理にかなっていることを願っており、データをスレッド proc に渡す方法を理解するのに役立つことを願っています。それがあなたの質問だと思います。
- 各スレッドに変数の個別のコピーが必要な場合は、変数をスレッド ローカルとして宣言します。
構造体を作ることができます。私は通常、globalArgs
そこにあるすべてのグローバル変数を置く場所と呼ばれる構造体を使用します。
このようなもの:
static typedef struct {
int foo;
int baa;
} globalargs;
または、必要な関数にすべての値をパラメーターとして渡すことができます。