https://ja.wikipedia.org/wiki/食事する哲学者の問題
この課題は「食事する哲学者の問題」という問題をthread(スレッド)という技術を使って並列処理で解こう、という課題です。まずはこれがどんな問題か理解しましょう。
問題が理解できたら、次はこの課題の新要素であるthread・mutexについて軽く理解しておきましょう。
例を用いて解説していきます。
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
void *routine(void *arg)
{
const int id = *(const int*)arg;
printf("This is thread %d\\n", id);
return NULL;
}
int main(void)
{
pthread_t thread;
int arg;
arg = 1;
pthread_create(&thread, NULL, routine, &arg);
pthread_join(thread, NULL);
return 0;
}
このコードの出力は
This is thread 1
となります。
何が起きているかというと、
pthread_t
型の変数をポインタ渡しNULL
でいいvoid *(func)(void *)
の型が必要void *
の型が必要pthread_t
型の変数NULL
でいいという流れです。
これだとただ渡された関数を実行するだけの何かなので、少し例を変えます。
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
void *routine(void *arg)
{
int *n = (int *)arg;
(*n)++;
return NULL;
}
int main(void)
{
pthread_t threads[10];
int n = 0;
for (int i = 0; i < 10; i++)
pthread_create(&threads[i], NULL, routine, &n);
for (int i = 0; i < 10; i++)
pthread_join(threads[i], NULL);
printf("n = %d\\n", n);
return 0;
}