source: libcf/trunk/test/log.c

Last change on this file was 157, checked in by cheese, 10 years ago

#1 fix memory leakage

File size: 2.2 KB
Line 
1/**
2 * @file log.c
3 * @author myusgun <myusgun@gmail.com>
4 */
5#include "cf_log.h"
6#include "cf_mutex.h"
7#include "cf_thread.h"
8#include "cf_debug.h"
9
10#include <stdio.h>
11
12#define COUNT 5
13
14cf_ctx globalLog;
15cf_ctx globalMutex;
16
17int worker (void * arg)
18{
19 static int cnt = 0;
20 int i = 0;
21 int th = 0;
22
23 if (CF_Mutex_Lock (globalMutex) < 0) { // for critical section
24 // error
25 }
26 th = cnt++;
27 if (CF_Mutex_Unlock (globalMutex) < 0) { // for critical section
28 // error
29 }
30
31 CF_DEBUG_PRINT (stderr, "created %dth thread\n", th);
32
33 for (i = 0 ; i < 10000 ; i++)
34 {
35 CF_Log_Write (globalLog, "LOG_MT", "[%d] multi-threadedlogging test %d\n", th, i);
36 }
37
38 CF_DEBUG_PRINT (stderr, "end %dth thread\n", th);
39
40 return 0;
41}
42
43int main (void)
44{
45 int i, j;
46 cf_ctx tid[COUNT];
47
48 /* initialize */
49 /* single thread {{{ */
50 if (CF_Log_Create (&globalLog, "log.txt", CF_LOG_NO_BUFFER) < 0)
51 CF_DEBUG_PRINT (stderr, "failed to open log\n");
52
53 for (j = 0 ; j < 10000 ; j++)
54 {
55 int result = CF_Log_Write (globalLog, "LOG_ID_TEST", "turn %d\n", j);
56 if (result < 0)
57 CF_DEBUG_PRINT (stderr, "failed to write log %d\n", result);
58 }
59
60 CF_Log_Destroy (globalLog);
61 /* }}} single thread */
62
63 /* mt {{{ */
64 if (CF_Log_Create (&globalLog, "log_mt.txt", CF_LOG_NO_BUFFER) < 0)
65 CF_DEBUG_PRINT (stderr, "create log ctx error\n");
66
67 if (CF_Mutex_Create (&globalMutex) < 0) {
68 // error
69 }
70
71 if (CF_Log_SetMultiThread (globalLog) < 0)
72 CF_DEBUG_PRINT (stderr, "set multi-threading mode error\n");
73
74 for (i = 0 ; i < COUNT ; i++)
75 {
76 if (CF_Thread_Create (&tid[i], worker, &i) < 0)
77 {
78 CF_DEBUG_PRINT (stderr, "failed to create %dth thread\n", i);
79 return -2;
80 }
81 }
82
83 for (i = 0 ; i < COUNT ; i++)
84 {
85 if (CF_Thread_Start (tid[i]) < 0)
86 {
87 CF_DEBUG_PRINT (stderr, "failed to start %dth thread\n", i);
88 return -3;
89 }
90 }
91
92 for (i = 0 ; i < COUNT ; i++)
93 {
94 if (CF_Thread_Join (tid[i]) < 0)
95 CF_DEBUG_PRINT (stderr, "failed to join %dth thread\n", i);
96 if (CF_Thread_Destroy (tid[i]) < 0)
97 CF_DEBUG_PRINT (stderr, "failed to release %dth thread\n", i);
98 }
99
100 if (CF_Log_UnsetMultiThread (globalLog) < 0)
101 CF_DEBUG_PRINT (stderr, "set multi-threading mode error\n");
102
103 if (CF_Mutex_Destory (globalMutex) < 0) {
104 // error
105 }
106 /* }}} mt */
107
108 /* finalize */
109 CF_Log_Destroy (globalLog);
110
111 return 0;
112}
Note: See TracBrowser for help on using the repository browser.