続いてはスレッド間で共有したいリソースがあるような場合。マルチプロセスではshmget(), shmat()を使って明示的に共有メモリーを確保する必要があったけど、マルチスレッドではプロセス内でグローバルな(?)変数を定義するだけでOK。
#include <stdio.h> #include <unistd.h> #include <pthread.h> #define THREADSNUM 5 void func(void); int res=0; int main(void){ pthread_t thread[THREADSNUM]; int i; for(i=0; i<THREADSNUM; i++){ pthread_create(&thread[i], NULL, (void *)func, NULL); } for(i=0; i<THREADSNUM; i++){ pthread_join(thread[i], NULL); } printf("end: res=%d\n", res); return 0; } void func(void) { int i; for(i=0; i<5; i++){ res++; } }
end: res=25
これは便利。