⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 programming.sgml

📁 eCos操作系统源码
💻 SGML
📖 第 1 页 / 共 4 页
字号:
<PROGRAMLISTING>#include &lt;cyg/kernel/kapi.h&#62;#include &lt;stdio.h&#62;#include &lt;math.h&#62;#include &lt;stdlib.h&#62;/* now declare (and allocate space for) some kernel objects,  like the two threads we will use */cyg_thread thread_s[2];	/* space for two thread objects */char stack[2][4096];	/* space for two 4K stacks *//* now the handles for the threads */cyg_handle_t simple_threadA, simple_threadB;/* and now variables for the procedure which is the thread */cyg_thread_entry_t simple_program;/* and now a mutex to protect calls to the C library */cyg_mutex_t cliblock;/* we install our own startup routine which sets up threads */void cyg_user_start(void){ printf("Entering twothreads' cyg_user_start() function\n"); cyg_mutex_init(&amp;cliblock); cyg_thread_create(4, simple_program, (cyg_addrword_t) 0,	"Thread A", (void *) stack[0], 4096,	&amp;simple_threadA, &amp;thread_s[0]); cyg_thread_create(4, simple_program, (cyg_addrword_t) 1,	"Thread B", (void *) stack[1], 4096,	&amp;simple_threadB, &amp;thread_s[1]); cyg_thread_resume(simple_threadA); cyg_thread_resume(simple_threadB);}/* this is a simple program which runs in a thread */void simple_program(cyg_addrword_t data){ int message = (int) data; int delay; printf("Beginning execution; thread data is %d\n", message); cyg_thread_delay(200); for (;;) { delay = 200 + (rand() % 50); /* note: printf() must be protected by a call to cyg_mutex_lock() */ cyg_mutex_lock(&amp;cliblock); { printf("Thread %d: and now a delay of %d clock ticks\n",	message, delay); } cyg_mutex_unlock(&amp;cliblock); cyg_thread_delay(delay); }}</PROGRAMLISTING><PARA>When you run the program (by typing <command>continue</command> atthe (<EMPHASIS>gdb</EMPHASIS>) prompt) the output should look likethis:</PARA><PROGRAMLISTING>Starting program: <replaceable>BASE_DIR</replaceable>/examples/twothreads.exeEntering twothreads' cyg_user_start()functionBeginning execution; thread data is 0Beginning execution; thread data is 1Thread 0: and now a delay of 240 clock ticksThread 1: and now a delay of 225 clock ticksThread 1: and now a delay of 234 clock ticksThread 0: and now a delay of 231 clock ticksThread 1: and now a delay of 224 clock ticksThread 0: and now a delay of 249 clock ticksThread 1: and now a delay of 202 clock ticksThread 0: and now a delay of 235 clock ticks</PROGRAMLISTING><NOTE><PARA>When running in a simulator the <!-- <index></index> -->delays might be quite long. On a hardware board (where the clockspeed is 100 ticks/second) the delays should average toabout 2.25 seconds. In simulation, the delay will depend on thespeed of the host processor and will almost always be much slower thanthe actual board. You might want to reduce the delay parameter when runningin simulation.</PARA></NOTE><PARA><XREF LINKEND="FIGURE-TWOTHREADS-WITH-SIMPLE-PRINTS"> shows how thismultitasking program executes.  Note that apart from the threadcreation system calls, this program also creates and uses a<EMPHASIS><!-- <index></index> -->mutex</EMPHASIS> for synchronizationbetween the <function>printf()</function> calls in the twothreads. This is because the C library standard I/O (by default) isconfigured not to be thread-safe, which means that if more than onethread is using standard I/O they might corrupt each other. This isfixed by a mutual exclusion (or <EMPHASIS>mutex</EMPHASIS>) lockoutmechanism: the threads do not call <function>printf()</function> until<function>cyg_mutex_lock()</function> has returned, which only happenswhen the other thread calls<function>cyg_mutex_unlock()</function>.</PARA><PARA>You could avoid using the mutex by configuring the C library tobe thread-safe (by selecting the component<LITERAL>CYGSEM_LIBC_STDIO_THREAD_SAFE_STREAMS</LITERAL>).</PARA><FIGUREID="FIGURE-TWOTHREADS-WITH-SIMPLE-PRINTS"><!-- <xref> --> <TITLE>Twothreads with simple print statements after random delays</TITLE><GRAPHIC ENTITYREF="programming-graphic9"></GRAPHIC></FIGURE></SECT2></SECT1></CHAPTER><!-- ==================================================== --><CHAPTER ID="CLOCKS-AND-ALARM-HANDLERS"><TITLE>More Features &mdash; <!-- <index></index> -->Clocks and AlarmHandlers</TITLE><PARA>If a program wanted to execute a task at a given time, orperiodically, it could do it in an inefficient way by sitting in aloop and checking the real-time clock to see if the proper amount oftime has elapsed. But operating systems usually provide system callswhich allow the program to be informed at the desired time.</PARA><PARA><productname>eCos</productname> provides a rich timekeeping formalism, involving<EMPHASIS>counters</EMPHASIS>, <EMPHASIS>clocks</EMPHASIS>,<EMPHASIS>alarms</EMPHASIS>, and <EMPHASIS>timers</EMPHASIS>.  Theprecise definition, relationship, and motivation of these features isbeyond the scope of this tutorial, but these examples illustrate howto set up basic periodic tasks.</PARA><PARA><!-- <index></index> -->Alarms are events that happen ata given time, either once or periodically. A thread associates analarm handling function with the alarm, so that the function willbe invoked every time the alarm &ldquo;goes off&rdquo;.</PARA><!-- ==================================================== --><SECT1 id="sample-alarms"><TITLE>A Sample Program with Alarms</TITLE><PARA><!-- <index></index> --><FILENAME>simple-alarm.c</FILENAME> (inthe examples directory) is a short program that creates a thread thatcreates an alarm. The alarm is handled by the function<FUNCTION>test_alarm_func()</FUNCTION>, which sets a globalvariable. When the main thread of execution sees that the variable haschanged, it prints a message.</PARA><EXAMPLE><TITLE>A sample <!-- <index></index> -->program that creates an alarm</TITLE><PROGRAMLISTING>/* this is a very simple program meant to demonstrate a basic use of time, alarms and alarm-handling functions  in eCos */#include &lt;cyg/kernel/kapi.h&#62;#include &lt;stdio.h&#62;#define NTHREADS 1#define STACKSIZE 4096static cyg_handle_t thread[NTHREADS];static cyg_thread thread_obj[NTHREADS];static char stack[NTHREADS][STACKSIZE];static void alarm_prog( cyg_addrword_t data );/* we install our own startup routine which sets up  threads and starts the scheduler */void cyg_user_start(void){ cyg_thread_create(4, alarm_prog, (cyg_addrword_t) 0,	"alarm_thread", (void *) stack[0],	STACKSIZE, &amp;thread[0], &amp;thread_obj[0]); cyg_thread_resume(thread[0]);}/* we need to declare the alarm handling function (which is defined below), so that we can pass it to  cyg_alarm_initialize() */cyg_alarm_t test_alarm_func;/* alarm_prog() is a thread which sets up an alarm which is then handled by test_alarm_func() */static void alarm_prog(cyg_addrword_t data){ cyg_handle_t test_counterH, system_clockH, test_alarmH; cyg_tick_count_t ticks; cyg_alarm test_alarm; unsigned how_many_alarms = 0, prev_alarms = 0, tmp_how_many; system_clockH = cyg_real_time_clock(); cyg_clock_to_counter(system_clockH, &amp;test_counterH); cyg_alarm_create(test_counterH, test_alarm_func,	(cyg_addrword_t) &amp;how_many_alarms,	&amp;test_alarmH, &amp;test_alarm); cyg_alarm_initialize(test_alarmH, cyg_current_time()+200, 200); /* get in a loop in which we read the current time and    print it out, just to have something scrolling by */ for (;;) {   ticks = cyg_current_time();   printf("Time is %llu\n", ticks);   /* note that we must lock access to how_many_alarms, since the   alarm handler might change it. this involves using the   annoying temporary variable tmp_how_many so that I can keep the   critical region short */   cyg_scheduler_lock();   tmp_how_many = how_many_alarms;   cyg_scheduler_unlock();   if (prev_alarms != tmp_how_many) {     printf(" --- alarm calls so far: %u\n", tmp_how_many);     prev_alarms = tmp_how_many;   }   cyg_thread_delay(30); }}/* test_alarm_func() is invoked as an alarm handler, so   it should be quick and simple. in this case it increments   the data that is passed to it. */void test_alarm_func(cyg_handle_t alarmH, cyg_addrword_t data){ ++*((unsigned *) data);}</PROGRAMLISTING></EXAMPLE><PARA>When you run this program (by typing <COMMAND>continue</COMMAND> atthe (<EMPHASIS>gdb</EMPHASIS>) prompt) the output should look likethis:</PARA><SCREEN>Starting program: <replaceable>BASE_DIR</replaceable>/examples/simple-alarm.exeTime is 0Time is 30Time is 60Time is 90Time is 120Time is 150Time is 180Time is 210  --- alarm calls so far: 1Time is 240Time is 270Time is 300Time is 330Time is 360Time is 390Time is 420  --- alarm calls so far: 2Time is 450Time is 480</SCREEN><NOTE><PARA>When running in a simulator the <!-- <index></index> --> delaysmight be quite long. On a hardware board (where the clock speed is 100ticks/second) the delays should average to about 0.3 seconds (and 2seconds between alarms). In simulation, the delay will depend on thespeed of the host processor and will almost always be much slower thanthe actual board. You might want to reduce the delay parameter whenrunning in simulation.</PARA></NOTE><PARA>Here are a few things you might notice about this program:</PARA><ITEMIZEDLIST><LISTITEM><PARA>It used the <function>cyg_real_time_clock()</function> function;this always returns a handle to the default system real-time <!--<index></index> --> clock. </PARA></LISTITEM><LISTITEM><PARA><!-- <index></index> -->Clocks are based on <!-- <index></index>--> counters, so the function <function>cyg_alarm_create()</function>uses a counter handle. The program used the function<function>cyg_clock_to_counter()</function> to strip the clock handleto the underlying counter handle. </PARA></LISTITEM><LISTITEM><PARA>Once the alarm is created it is <!-- <index></index> -->initialized with <function>cyg_alarm_initialize()</function>, whichsets the time at which the alarm should go off, as well as the periodfor repeating alarms. It is set to go off at the current time andthen to repeat every 200 ticks. </PARA></LISTITEM><LISTITEM><PARA>The alarm handler function<function>test_alarm_func()</function> conforms to the guidelines forwriting alarm handlers and other <!-- <index></index> --><!--<index></index> --> delayed service routines: it does not invoke anyfunctions which might lock the scheduler.  This is discussed in detailin the <CITETITLE><productname>eCos</productname> Reference Manual</CITETITLE>, in the chapter<citetitle>The <productname>eCos</productname> Kernel</citetitle>.</PARA></LISTITEM><LISTITEM><PARA>There is a <EMPHASIS>critical region</EMPHASIS> in this program:the variable <LITERAL>how_many_alarms</LITERAL> is accessed in themain thread of control and is also modified in the alarm handler. Toprevent a possible (though unlikely) race condition on this variable,access to <LITERAL>how_many_alarms</LITERAL> in the principal threadis protected by calls to <FUNCTION>cyg_scheduler_lock()</FUNCTION> and<FUNCTION>cyg_scheduler_unlock()</FUNCTION>. When the scheduler islocked, the alarm handler will not be invoked, so the problem isaverted. </PARA></LISTITEM></ITEMIZEDLIST></SECT1></CHAPTER></part>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -