/** * @file log.c * @author myusgun */ #include "cf_log.h" #include "cf_mutex.h" #include "cf_thread.h" #include "cf_debug.h" #include #define COUNT 5 cf_ctx globalLog; cf_ctx globalMutex; int worker (void * arg) { static int cnt = 0; int i = 0; int th = 0; if (CF_Mutex_Lock (globalMutex) < 0) { // for critical section // error } th = cnt++; if (CF_Mutex_Unlock (globalMutex) < 0) { // for critical section // error } CF_DEBUG_PRINT (stderr, "created %dth thread\n", th); for (i = 0 ; i < 10000 ; i++) { CF_Log_Write (globalLog, "LOG_MT", "[%d] multi-threadedlogging test %d\n", th, i); } CF_DEBUG_PRINT (stderr, "end %dth thread\n", th); return 0; } int main (void) { int i, j; cf_ctx tid[COUNT]; /* initialize */ if (CF_Log_Create (&globalLog, "log.txt", CF_LOG_NO_BUFFER) < 0) CF_DEBUG_PRINT (stderr, "failed to open log\n"); for (j = 0 ; j < 10000 ; j++) { int result = CF_Log_Write (globalLog, "LOG_ID_TEST", "turn %d\n", j); if (result < 0) CF_DEBUG_PRINT (stderr, "failed to write log %d\n", result); } /* mt {{{ */ if (CF_Log_Create (&globalLog, "log_mt.txt", CF_LOG_NO_BUFFER) < 0) CF_DEBUG_PRINT (stderr, "create log ctx error\n"); if (CF_Mutex_Create (&globalMutex) < 0) { // error } if (CF_Log_SetMultiThread (globalLog) < 0) CF_DEBUG_PRINT (stderr, "set multi-threading mode error\n"); for (i = 0 ; i < COUNT ; i++) { if (CF_Thread_Create (&tid[i], worker, &i) < 0) { CF_DEBUG_PRINT (stderr, "failed to create %dth thread\n", i); return -2; } } for (i = 0 ; i < COUNT ; i++) { if (CF_Thread_Start (tid[i]) < 0) { CF_DEBUG_PRINT (stderr, "failed to start %dth thread\n", i); return -3; } } for (i = 0 ; i < COUNT ; i++) { if (CF_Thread_Join (tid[i]) < 0) CF_DEBUG_PRINT (stderr, "failed to join %dth thread\n", i); if (CF_Thread_Destroy (tid[i]) < 0) CF_DEBUG_PRINT (stderr, "failed to release %dth thread\n", i); } if (CF_Log_UnsetMultiThread (globalLog) < 0) CF_DEBUG_PRINT (stderr, "set multi-threading mode error\n"); if (CF_Mutex_Destory (globalMutex) < 0) { // error } /* }}} mt */ /* finalize */ CF_Log_Destroy (globalLog); return 0; }