source: libcf/trunk/test/log.c@ 151

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

#1 fix interface and add util module

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 if (CF_Log_Create (&globalLog, "log.txt", CF_LOG_NO_BUFFER) < 0)
50 CF_DEBUG_PRINT (stderr, "failed to open log\n");
51
52 for (j = 0 ; j < 10000 ; j++)
53 {
54 int result = CF_Log_Write (globalLog, "LOG_ID_TEST", "turn %d\n", j);
55 if (result < 0)
56 CF_DEBUG_PRINT (stderr, "failed to write log %d\n", result);
57 }
58
59 /* mt {{{ */
60 if (CF_Log_Create (&globalLog, "log_mt.txt", CF_LOG_NO_BUFFER) < 0)
61 CF_DEBUG_PRINT (stderr, "create log ctx error\n");
62
63 if (CF_Mutex_Create (&globalMutex) < 0) {
64 // error
65 }
66
67 if (CF_Log_SetMultiThread (globalLog) < 0)
68 CF_DEBUG_PRINT (stderr, "set multi-threading mode error\n");
69
70 for (i = 0 ; i < COUNT ; i++)
71 {
72 if (CF_Thread_Create (&tid[i], worker, &i) < 0)
73 {
74 CF_DEBUG_PRINT (stderr, "failed to create %dth thread\n", i);
75 return -2;
76 }
77 }
78
79 for (i = 0 ; i < COUNT ; i++)
80 {
81 if (CF_Thread_Start (tid[i]) < 0)
82 {
83 CF_DEBUG_PRINT (stderr, "failed to start %dth thread\n", i);
84 return -3;
85 }
86 }
87
88 for (i = 0 ; i < COUNT ; i++)
89 {
90 if (CF_Thread_Join (tid[i]) < 0)
91 CF_DEBUG_PRINT (stderr, "failed to join %dth thread\n", i);
92 if (CF_Thread_Destroy (tid[i]) < 0)
93 CF_DEBUG_PRINT (stderr, "failed to release %dth thread\n", i);
94 }
95
96 if (CF_Log_UnsetMultiThread (globalLog) < 0)
97 CF_DEBUG_PRINT (stderr, "set multi-threading mode error\n");
98
99 if (CF_Mutex_Destory (globalMutex) < 0) {
100 // error
101 }
102 /* }}} mt */
103
104 /* finalize */
105 CF_Log_Destroy (globalLog);
106
107 return 0;
108}
Note: See TracBrowser for help on using the repository browser.