编程范式16 笔记 信号量

来源:互联网 发布:小怪兽 知乎 编辑:程序博客网 时间:2024/06/08 09:25
void SellTickets(int i,int TicketsToSell,int numTickets,Samephore lock){    while(True){       /*临界区开始*/        SamephoreWait(lock);        (*numTickets)--;        SamephoreSignal(lock);        /*临界区结束*/        printf("all done\n");    }}

信号量要大于0
假设有两个线程都卖出票,那么写回会出问题

http 并行化

char buffer[8];int main(){    ITP(false);//init thread package    ThreadNew("writer",writer,0);    ThreadNew("Reader",Reader,0);    RunAllThread();}void writer(){    for(int i=0;i<40;i++){        char=PrepareRondomChar();        buffer[i%8]=c;    }}void Reader(){    for(int i=0;i<40;i++){        char c=buffer[i%8];        ProcessChar(c);    }}

要保证reader比writer慢
但是buffer有限
writer又不能快太多

char buffer[8];Samphore emptyBuffers 8;//Samphore emptyBuffers 4 自由度降低 正确性不影响//Samphore emptyBuffers 0 死锁Samphore fullBuffers 0;//Samphore fullBuffers 1;出错 Reader可能领先int main(){    ITP(false);//init thread package    ThreadNew("writer",writer,0);    ThreadNew("Reader",Reader,0);    RunAllThread();}void writer(){    for(int i=0;i<40;i++){        SamphoreWait(emptyBuffers);         char=PrepareRondomChar();        SamphoreSignal(fullBuffers);        buffer[i%8]=c;    }}void Reader(){    for(int i=0;i<40;i++){        SamphoreWait(fullBuffers);         char c=buffer[i%8];        SamphoreSignal(emptyBuffers);        ProcessChar(c);    }}

哲学家吃饭

Samaphore forks[]={1,1,1,1,1}Semaphore numOfForkToEat(4);Semaphore void philosopter(int id){    for(int i=0;i<3;i++){        sw(forks[i]);        sw(forks[(i+1)%5];        Eat;        ss(forks[i]);        ss(forks[(i+1)%5]);
原创粉丝点击