目次

どこから始める?

課題の概要

https://ja.wikipedia.org/wiki/食事する哲学者の問題

この課題は「食事する哲学者の問題」という問題をthread(スレッド)という技術を使って並列処理で解こう、という課題です。まずはこれがどんな問題か理解しましょう。

問題が理解できたら、次はこの課題の新要素であるthreadmutexについて軽く理解しておきましょう。

thread

例を用いて解説していきます。

#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

となります。

何が起きているかというと、

という流れです。

これだとただ渡された関数を実行するだけの何かなので、少し例を変えます。

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