スレッドとグローバル変数を使用してタスクを完了するにはどうすればよいですか?
あなたがLinux
を使用している場合は、C
プログラミング言語のスレッドのためPOSIX
ライブラリを使用することができます。ライブラリは<pthread.h>
です。しかし、代わりに、移植可能で比較的非侵入型のライブラリで、gcc
とg++
でよくサポートされていて、MSVCの(旧バージョンの)ライブラリはopenMPです。
標準CおよびC++ではありませんが、OpenMP自体は標準です。
どのようにスレッドを希望の順序でLinuxでスケジュールできますか?
印刷を行うには、2つのスレッドでアクセスできるグローバル変数が必要です。両方のスレッドが交互にグローバル変数variable
にアクセスし、操作を実行します(increment
およびprint
)。ただし、desired order
を達成するには、mutex
が必要です。ミューテックスは相互排除セマフォーであり、一度に1つのロッカーしか許可しないセマフォの特殊な変形です。これは、リソースのインスタンス(global variable in your case
)があり、そのリソースが2つのスレッドによって共有されている場合に使用できます。そのミューテックスをロックした後のスレッドは、リソースのインスタンスへの排他的なアクセスを持つことができ、その操作を完了した後、スレッドは他のスレッドのためにミューテックスを解放する必要があります。
<pthread.h>
のスレッドとmutexは、hereから開始できます。
問題の解決策の1つがこのプログラムである可能性があります。しかし、私はあなた自身がそれを試してみることを提案し、次に私の解決策を見てください。
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t lock;
int variable=0;
#define ONE_TIME_INC 5
#define MAX 100
void *thread1(void *arg)
{
while (1) {
pthread_mutex_lock(&lock);
printf("Thread1: \n");
int i;
for (i=0; i<ONE_TIME_INC; i++) {
if (variable >= MAX)
goto RETURN;
printf("\t\t%d\n", ++variable);
}
printf("Thread1: Sleeping\n");
pthread_mutex_unlock(&lock);
usleep(1000);
}
RETURN:
pthread_mutex_unlock(&lock);
return NULL;
}
void *thread2(void *arg)
{
while (1) {
pthread_mutex_lock(&lock);
printf("Thread2: \n");
int i;
for (i=0; i<ONE_TIME_INC; i++) {
if (variable >= MAX)
goto RETURN;
printf("%d\n", ++variable);
}
printf("Thread2: Sleeping\n");
pthread_mutex_unlock(&lock);
usleep(1000);
}
RETURN:
pthread_mutex_unlock(&lock);
return NULL;
}
int main()
{
if (pthread_mutex_init(&lock, NULL) != 0) {
printf("\n mutex init failed\n");
return 1;
}
pthread_t pthread1, pthread2;
if (pthread_create(&pthread1, NULL, thread1, NULL))
return -1;
if (pthread_create(&pthread2, NULL, thread2, NULL))
return -1;
pthread_join(pthread1, NULL);
pthread_join(pthread2, NULL);
pthread_mutex_destroy(&lock);
return 0;
}
の可能性のある重複[Cスレッドプログラミング - 共有変数をインクリメント(http://stackoverflow.com/questions/1533390/c-threaded-programming-incrementing-a-shared-variable ) – LPs