/* kmt.c * マルチスレッドのサンプル * ・使用するスレッド数を設定 */ #define USAGE "Usage: kmt " #include #include "apr_general.h" #include "apr_errno.h" #include "apr_file_io.h" #include "apr_thread_proc.h" #include "mytt.h" #include "mystab.h" /* サブスレッドで使うデータの構造体 */ typedef struct _do_it_data_st { int job_id; /* メインスレッドで付与する値 */ apr_file_t *out; /* 出力先ファイルハンドラ */ } do_it_data; /* サブスレッドの処理内容 */ static void* APR_THREAD_FUNC do_it( apr_thread_t *thd /* サブスレッドのスレッドハンドラ */ , void *data /* 使用するデータ */ ) { do_it_data *did = (do_it_data*)data; apr_file_printf(did->out, "\tjob_id=[%02d] START.\n", did->job_id); apr_sleep(1000000); /* 1000000マイクロ秒=1秒スリープ */ apr_file_printf(did->out, "\tjob_id=[%02d] END.\n", did->job_id); apr_thread_exit(thd, APR_SUCCESS); /* 【必須】サブスレッドの終了 */ return NULL; } int apr_my_main ( int ac, char **av , apr_file_t * astdin , apr_file_t * astdout , apr_file_t * astderr , apr_pool_t * pool ) { apr_status_t rv = APR_SUCCESS; int n_threads = 0; int i=0; my_thread_table mtt; apr_thread_t *thd = NULL; if (ac < 2) { apr_file_printf(astderr, "%s\n", USAGE); return 1; /* 異常終了 */ } n_threads = atoi(av[1]); if (n_threads <= 0) { apr_file_printf(astderr, "ERROR: abnormal num_threads\n"); return 1; /* 異常終了 */ } /* スレッドテーブルの初期化 */ /* memset(&mtt, 0, sizeof(my_thread_table)); */ my_thread_table_init(&mtt, n_threads, pool); /* 100個の処理をサブスレッドに並行処理させる。 */ for (i=0; i<100; i++) { do_it_data *did = (do_it_data*)apr_palloc(pool, sizeof(do_it_data)); did->job_id=i; did->out = astdout; if(1)apr_file_printf(astdout, "##job_id=[%d]\n", i); /* サブスレッドの生成 */ rv = my_thread_create (&mtt, &thd, do_it, (void*)did); if (rv != APR_SUCCESS) { char error_buf[32]; apr_file_printf(astderr, "%s\n", apr_strerror(rv, error_buf, sizeof(error_buf))); /* エラーを検出しても続ける。もちろん、ここでループを抜けてもよい。 */ } } /* スレッドテーブルのリセット(全サブスレッドの同期) */ rv = my_thread_table_clear(&mtt); if (rv != APR_SUCCESS) { char error_buf[32]; apr_file_printf(astderr, "%s\n", apr_strerror(rv, error_buf, sizeof(error_buf))); apr_file_printf(astderr, "failed!\n"); return 1; /* 異常終了 */ } apr_file_printf(astdout, "\ndone.\n"); return 0; /* 正常終了 */ } /* end of main */