|
| 1 | +#include <string.h> |
| 2 | +#include <stdio.h> |
| 3 | +#include <LCUI_Build.h> |
| 4 | +#include <LCUI/LCUI.h> |
| 5 | +#include <LCUI/thread.h> |
| 6 | +#include "test.h" |
| 7 | + |
| 8 | +typedef struct TestWorkerRec_ { |
| 9 | + char data[32]; |
| 10 | + int data_count; |
| 11 | + LCUI_BOOL active; |
| 12 | + LCUI_Cond cond; |
| 13 | + LCUI_Mutex mutex; |
| 14 | + LCUI_Thread thread; |
| 15 | +} TestWorkerRec, *TestWorker; |
| 16 | + |
| 17 | +static void TestWorker_Thread( void *arg ) |
| 18 | +{ |
| 19 | + TestWorker worker = arg; |
| 20 | + |
| 21 | + worker->active = TRUE; |
| 22 | + worker->data_count = 0; |
| 23 | + LCUIMutex_Lock( &worker->mutex ); |
| 24 | + while( worker->active ) { |
| 25 | + TEST_LOG( "waiting...\n" ); |
| 26 | + LCUICond_Wait( &worker->cond, &worker->mutex ); |
| 27 | + TEST_LOG( "get data: %s\n", worker->data ); |
| 28 | + worker->data_count += 1; |
| 29 | + } |
| 30 | + LCUIMutex_Unlock( &worker->mutex ); |
| 31 | + TEST_LOG( "count: %lu\n", worker->data_count ); |
| 32 | +} |
| 33 | + |
| 34 | +static void TestWorker_Send( TestWorker worker, const char *data ) |
| 35 | +{ |
| 36 | + LCUIMutex_Lock( &worker->mutex ); |
| 37 | + strcpy( worker->data, data ); |
| 38 | + LCUICond_Signal( &worker->cond ); |
| 39 | + LCUIMutex_Unlock( &worker->mutex ); |
| 40 | +} |
| 41 | + |
| 42 | +static void TestWorker_Init( TestWorker worker ) |
| 43 | +{ |
| 44 | + LCUIMutex_Init( &worker->mutex ); |
| 45 | + LCUICond_Init( &worker->cond ); |
| 46 | +} |
| 47 | + |
| 48 | +static void TestWorker_Destroy( TestWorker worker ) |
| 49 | +{ |
| 50 | + LCUIMutex_Lock( &worker->mutex ); |
| 51 | + worker->active = FALSE; |
| 52 | + LCUICond_Signal( &worker->cond ); |
| 53 | + LCUIMutex_Unlock( &worker->mutex ); |
| 54 | + LCUIThread_Join( worker->thread, NULL ); |
| 55 | + LCUIMutex_Destroy( &worker->mutex ); |
| 56 | + LCUICond_Destroy( &worker->cond ); |
| 57 | +} |
| 58 | + |
| 59 | +int test_thread( void ) |
| 60 | +{ |
| 61 | + int ret = 0; |
| 62 | + TestWorkerRec worker; |
| 63 | + |
| 64 | + TestWorker_Init( &worker ); |
| 65 | + LCUIThread_Create( &worker.thread, TestWorker_Thread, &worker ); |
| 66 | + LCUI_Sleep( 1 ); |
| 67 | + TestWorker_Send( &worker, "hello" ); |
| 68 | + LCUI_MSleep( 200 ); |
| 69 | + TestWorker_Send( &worker, "world" ); |
| 70 | + LCUI_Sleep( 1 ); |
| 71 | + TestWorker_Send( &worker, "this" ); |
| 72 | + LCUI_MSleep( 500 ); |
| 73 | + TestWorker_Send( &worker, "is" ); |
| 74 | + LCUI_Sleep( 1 ); |
| 75 | + TestWorker_Send( &worker, "test" ); |
| 76 | + LCUI_MSleep( 100 ); |
| 77 | + TestWorker_Send( &worker, "bye!" ); |
| 78 | + LCUI_Sleep( 1 ); |
| 79 | + TestWorker_Destroy( &worker ); |
| 80 | + CHECK( worker.data_count == 7 ); |
| 81 | + return ret; |
| 82 | +} |
0 commit comments