関数ポインタめんどくせえ、無名関数作らせろって感じです!!
- プログラムの命令やグローバルデータのようなものはプロセスに収める
- プログラムカウンタやスタックといった実行状態に関連する情報はスレッドに収める
#include <iostream> #include <pthread.h> void* do_one_thing(void *arg) { int *pnum_times = (int *) arg; int x = 0; for(int i = 0; i < 4; i++) { std::cout << "doing one thing" << std::endl; for(int j = 0; j < 10000; j++) x++; (*pnum_times)++; } }; void* do_another_thing(void *arg) { int *pnum_times = (int *) arg; int x = 0; for(int i = 0; i < 4; i++) { std::cout << "doing another thing" << std::endl; for(int j = 0; j < 10000; j++) x++; (*pnum_times)++; } }; void do_wrap_up(int one_times, int another_times) { int total = 0; total = one_times + another_times; std::cout << "All done, one thing " << one_times << " another " << another_times << " for a total of " << total << std::endl; }; int main(int argc, char *argv[]) { pthread_t thread1, thread2; int r1 = 0, r2 = 0; pthread_create(&thread1, NULL, do_one_thing, (void *) &r1); pthread_create(&thread2, NULL, do_another_thing, (void *) &r2); pthread_join(thread1, NULL); pthread_join(thread2, NULL); do_wrap_up(r1, r2); };
/Users/syou6162/cpp% ./a.out doing one thing doing one thing doing one thing doing one thing doing another thing doing another thing doing another thing doing another thing All done, one thing 4 another 4 for a total of 8
#include <iostream> #include <pthread.h> pthread_t thread1, thread2; pthread_mutex_t r3_mutex; int r1 = 0, r2 = 0, r3 = 0; void* do_one_thing(void *arg) { int *pnum_times = (int *) arg; int x = 0; pthread_mutex_lock(&r3_mutex); if (r3 > 3) { x = r3; r3--; } else { x = 1; } pthread_mutex_unlock(&r3_mutex); for (int i = 0; i < 4; i++) { sleep(1); std::cout << "doing one thing" << std::endl; (*pnum_times)++; } }; void* do_another_thing(void *arg) { int *pnum_times = (int *) arg; int x = 0; for(int i = 0; i < 4; i++) { std::cout << "doing another thing" << std::endl; for(int j = 0; j < 10000; j++) x++; (*pnum_times)++; } }; void do_wrap_up(int one_times, int another_times) { int total = 0; total = one_times + another_times; std::cout << "All done, one thing " << one_times << " another " << another_times << " for a total of " << total << std::endl; }; int main(int argc, char *argv[]) { pthread_create(&thread1, NULL, do_one_thing, (void *) &r1); pthread_create(&thread2, NULL, do_another_thing, (void *) &r2); pthread_join(thread1, NULL); pthread_join(thread2, NULL); do_wrap_up(r1, r2); };
/Users/syou6162/cpp% ./a.out doing another thing doing another thing doing another thing doing another thing doing one thing doing one thing doing one thing doing one thing All done, one thing 4 another 4 for a total of 8