3.3.2 マルチスレッド対応のユーザアプリケーションプログラムの作成
マルチスレッドで動作するCUPのコーディング例を示します。この例は,CUPから送信したメッセージをエコーバックするSPPを呼び出すプログラムです。
000010 #include <stdio.h> 000020 #include <string.h> 000030 #include <dcvclt.h> 000040 #include <dcvrpc.h> 000050 #include <pthread.h> 000060 #include <sys/errno.h> 000070 #define BUFSIZE 512 000080 #define SERVICE "spp01" 000090 #define THDMAX 5 000100 000110 void *CUP_thread(void *arg) 000120 { 000130 char in[BUFSIZE]; 000140 DCULONG in_len; 000150 char out[BUFSIZE]; 000160 DCULONG out_len; 000170 int rc = DC_OK; 000180 DCCLT_ID cltid; 000190 int myid; 000200 000210 myid = *((int *)arg); 000220 000230 /*--- クライアントユーザの認証要求 ---*/ 000240 if ((rc = dc_clt_cltin_s(NULL, &cltid, NULL, NULL, 000250 "user01", "puser01", NULL, DCNOFLAGS)) != DC_OK) { 000260 printf("cup%d: dc_clt_cltinに失敗しました。CODE=%d\n", myid, rc); 000270 goto PROG_EXIT; 000280 } 000290 000300 /*--- RPC-OPEN (RPC環境の初期設定) ---*/ 000310 if ((rc = dc_rpc_open_s(cltid, DCNOFLAGS)) != DC_OK) { 000320 printf("cup%d: dc_rpc_openに失敗しました。CODE=%d\n", myid, rc); 000330 goto PROG_END; 000340 } 000350 000360 /*--- RPC-CALL (RPCの実行) ---*/ 000370 strcpy(in, "HELLO SPP !!"); 000380 in_len = strlen(in) + 1; 000390 out_len = sizeof(out); 000400 if ((rc = dc_rpc_call_s(cltid, SERVICE, "echo", in, &in_len, 000410 out, &out_len, DCNOFLAGS)) != DC_OK) { 000420 printf("cup%d: dc_rpc_callに失敗しました。CODE=%d\n", myid, rc); 000430 goto PROG_END; 000440 } 000450 printf("%s\n", out); 000460 PROG_END: 000470 000480 /*--- RPC-CLOSE(RPC環境の解除)---*/ 000490 dc_rpc_close_s(cltid, DCNOFLAGS); 000500 000510 PROG_EXIT: 000520 /*--- クライアントユーザの認証解除 ---*/ 000530 dc_clt_cltout_s(cltid, DCNOFLAGS); 000540 000550 /*--- スレッドを終了させる ---*/ 000560 pthread_exit(arg); 000570 } 000580 000590 main() 000600 { 000610 int i; 000620 int rc; 000630 int *exit_value; 000640 pthread_t threads[THDMAX]; 000650 000660 /*--- スレッドを生成する ---*/ 000670 for (i = 1; i < THDMAX; i++) { 000680 rc = pthread_create((pthread_t *)&threads[i], 000690 NULL, 000700 CUP_thread, 000710 (void *)&i); 000720 if (rc < 0) { 000730 printf("cup0: pthread_createに失敗しました。CODE=%d\n", errno); 000740 } 000750 } 000760 000770 /*--- スレッドの終了を待ち合わせる ---*/ 000780 for (i = 1; i < THDMAX; i++) { 000790 rc = pthread_join(threads[i], (void **)&exit_value); 000800 if (rc < 0) { 000810 printf("cup0: pthread_joinに失敗しました。CODE=%d\n", errno); 000820 } 000830 } 000840 }