Protothreads

Protothreads是个好东西,
官网在此 http://www.sics.se/~adam/pt/index.html

二话不说,上代码
#include  " pt.h "  
#include 
< stdio.h >
#include 
< stdlib.h >

static    int   countrer;  
 
  
PT_THREAD( example(
struct   pt   * pt1) )  
{  
    
int  i  =   0 ;
    PT_BEGIN(pt1);  

    i 
=   100 ;
    printf(
" before i = %d\n " , i);

    PT_WAIT_UNTIL(pt1, countrer 
==   5  );  
    
    printf(
" Threshold reached\n " );  
    printf(
" after i = %d\n " , i);

    PT_END(pt1);  
}  

int  main( void )  
{  
    
static    struct   pt  example_pt; 
    countrer 
=   0 ;  
    PT_INIT(
& example_pt);  
    
    
while ( 1 )
    {
        
if ( PT_ENDED  ==  example( & example_pt) )
            
break ;

        countrer
++ ;  
    }

    
return   0 ;  
}  

原理很简单, 宏展开就是
#include  < stdio.h >
#include 
< stdlib.h >

#define  PT_WAITING 0
#define  PT_ENDED 3

typedef unsigned 
short  lc_t;
struct  pt 
{
    lc_t lc;
};

static    int   countrer;  
  
char  example( struct   pt   * pt1)
{  
    
int  i  =   0 ;

//////////////////////////////////////////////////////////////////////// // begin
    { 
        
switch ((pt1) -> lc) 
        {     
        
case   0 :
//////////////////////////////////////////////////////////////////////// // -begin

            
while ( 1
            {  
//////////////////////////////////////////////////////////////////////// // call
                 do  {        
                    (pt1)
-> lc  =  __LINE__;  case  __LINE__:

                    
if ! ( countrer  ==   5  ) ) 
                    {
                        
return  PT_WAITING;    
                    }                        
                } 
while ( 0 );
//////////////////////////////////////////////////////////////////////// // -call

                printf(
" Threshold reached\n " );  
                countrer 
=   0 ;  
                exit(
1 );
            }  

//////////////////////////////////////////////////////////////////////// // end
        } 
        (pt1)
-> lc  =   0 ;
        
return  PT_ENDED;
    }
//////////////////////////////////////////////////////////////////////// // -end
}

int  main( void )  
{  
    
static    struct   pt  example_pt; 
    countrer 
=   0 ;  

    (
& example_pt) -> lc  =   0 ;
    
    
while ( 1 )
    {
        example(
& example_pt);  
        countrer
++ ;  
    }

    
return   0 ;  
}  

有个坏处, 写代码时
 i = 100;                                      <----- 这里赋了值
 printf("before i = %d\n", i);


到了
 printf("Threshold reached\n"); 
 printf("after i = %d\n", i);              <----- 到了这里你还以为i 是 100? 错了....

不过用于解决 
http://www.cppblog.com/sleepwom/archive/2013/05/19/200390.html 
我在这篇文章提出的问题, 提供了一种思路.

你可能感兴趣的:(Protothreads)