mt-test.c
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046 #include <stdio.h>
00047
00048 #include "contiki.h"
00049 #include "ctk.h"
00050 #include "sys/mt.h"
00051 #include "mtarch.h"
00052
00053 #define WIN_XSIZE 10
00054 #define WIN_YSIZE 10
00055
00056 static char log[WIN_XSIZE * WIN_YSIZE];
00057 static struct ctk_window window;
00058 static struct ctk_label loglabel = {CTK_LABEL(0, 0, WIN_XSIZE, WIN_YSIZE, log)};
00059 PROCESS(mt_process, "Multi-threading test");
00060
00061 static char buf[20];
00062
00063 void
00064 println(char *str1)
00065 {
00066 unsigned int i;
00067
00068 for(i = 1; i < WIN_YSIZE; i++) {
00069 memcpy(&log[(i - 1) * WIN_XSIZE], &log[i * WIN_XSIZE], WIN_XSIZE);
00070 }
00071 memset(&log[(WIN_YSIZE - 1) * WIN_XSIZE], 0, WIN_XSIZE);
00072
00073 strncpy(&log[(WIN_YSIZE - 1) * WIN_XSIZE], str1, WIN_XSIZE);
00074
00075 CTK_WIDGET_REDRAW(&loglabel);
00076 }
00077
00078 static void
00079 thread_func(char *str, int len)
00080 {
00081 println((char *) (str + len));
00082 mt_yield();
00083
00084 if(len) {
00085 thread_func(str, len - 1);
00086 mt_yield();
00087 }
00088
00089 println((char *) (str + len));
00090 }
00091
00092 static void
00093 thread_main(void *data)
00094 {
00095 while(1) {
00096 thread_func((char *)data, 9);
00097 }
00098 mt_exit();
00099 }
00100
00101
00102 PROCESS_THREAD(mt_process, ev, data)
00103 {
00104
00105 static struct etimer timer;
00106 static int toggle = 0;
00107 static struct mt_thread th1;
00108 static struct mt_thread th2;
00109
00110 PROCESS_BEGIN();
00111
00112 ctk_window_new(&window, WIN_XSIZE, WIN_YSIZE, "Multithread");
00113 CTK_WIDGET_ADD(&window, &loglabel);
00114 memset(log, 0, sizeof(log));
00115 ctk_window_open(&window);
00116 mt_init();
00117 mt_start(&th1, thread_main, "JIHGFEDCBA");
00118 mt_start(&th2, thread_main, "9876543210");
00119
00120 etimer_set(&timer, CLOCK_SECOND / 2);
00121 while(1) {
00122 PROCESS_WAIT_EVENT();
00123 if(ev == PROCESS_EVENT_TIMER) {
00124 if(toggle) {
00125 mt_exec(&th1);
00126 toggle--;
00127 } else {
00128 mt_exec(&th2);
00129 toggle++;
00130 }
00131 etimer_set(&timer, CLOCK_SECOND / 2);
00132 } else if(ev == ctk_signal_window_close || ev == PROCESS_EVENT_EXIT) {
00133 ctk_window_close(&window);
00134 process_exit(&mt_process);
00135 LOADER_UNLOAD();
00136 }
00137 }
00138
00139 mt_stop(&th1);
00140 mt_stop(&th2);
00141 mt_remove();
00142
00143 while(1) {
00144 PROCESS_WAIT_EVENT();
00145 }
00146 PROCESS_END();
00147 }
00148