惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 聂微东
宝玉的分享
宝玉的分享
Apple Machine Learning Research
Apple Machine Learning Research
罗磊的独立博客
Last Week in AI
Last Week in AI
WordPress大学
WordPress大学
博客园 - 【当耐特】
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
博客园 - 司徒正美
博客园 - Franky
爱范儿
爱范儿
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Tailwind CSS Blog
Hugging Face - Blog
Hugging Face - Blog
Jina AI
Jina AI
量子位
博客园 - 叶小钗
博客园_首页
月光博客
月光博客
博客园 - 三生石上(FineUI控件)
The Cloudflare Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报

博客园 - 飘啊飘

一个精简的vi源码(2000行) dtruss 粗糙的翻译 gdb常用命令[转] gdb中信号的处理[转] 在linux中通过进程名获得进程id busybox0.60.3源码学习开始 pygame做的贪吃蛇 python中使用struct模块处理二进制数据 使用PYGAME开发的坦克游戏[代码][思路] 一篇很好的讲/etc/inittab的文章[转] 《代码整洁之道》笔记之函数 使用面向对象概念优化条件判断语句的一个小应用 python生成文件树的代码 深入理解软件包的配置、编译与安装[转] pygame学习之对象移动 pywin32重启电脑 - 飘啊飘 - 博客园 解决LINUX和WINDOWS时间不一置 通过状态机实现的一个配置读取函数 UNIX基础知识--《APUE》第一章笔记
哲学家吃空心粉问题
飘啊飘 · 2011-04-29 · via 博客园 - 飘啊飘

//      pe.c
//      哲学家吃空心粉的问题
//      Copyright 2011 shiweifu <shiweifu@126.com>
//      

#define _REENTRANT
#include 
<stdio.h>
#include 
<unistd.h>
#include 
<stdlib.h>
#include 
<string.h>

#include 

<semaphore.h>
#include 
<pthread.h>#define STR_MAX 256

typedef 

struct philosophy {
    
char name[STR_MAX];
    sem_t 
*left;
    sem_t 
*right;
    
char is_stop;
} philosophy;
void *thread_function(void *arg);int main(int argc, char **argv) {    
    
    
int i = 0;
    
//五只悲剧的筷子
    sem_t sems[5];
    
//五个NC哲学家
    philosophy philers[5];
    
    pthread_t threads[
5];
    
    
int res = 0;
    
    
char tmp[255= {0};
    
    
for(; i < 5; i++) {
        philers[i].left 
= &sems[i];
        philers[i].right 
= &sems[i];
        
        
if (i == 4) {
            philers[i].left 
= &sems[0];
        }
        philers[i].is_stop 
= 0;
        sprintf(tmp,
"NC %d",i);
        strncpy(philers[i].name,tmp,
255);
    }
    
for(i = 0; i < 5; i++) {
        sem_init(
&sems[i], 010);

        res 

= pthread_create(&threads[i],NULL,thread_function,&philers[i]);
        
if (res != 0) {
            perror(
"创建线程出错啦...");
        }
    }
    
    
//给这群吃货吃20秒
    sleep(20);
    
    
for(i = 0; i < 5; i++) {
        philers[i].is_stop 
= 1;
        pthread_join(threads[i],NULL);
        
    }
    
for(i = 0; i < 5; i++) {
        sem_destroy(
&sems[i]);
    }

    exit(EXIT_SUCCESS);
}

void *thread_function(void *arg) {
    philosophy 
*= arg;
    
    
while (1) {
        
if (sem_trywait(p->left) == 0) {
            
if (sem_trywait(p->right) == 0) {
                printf(
"红烧翅膀真好吃,我是%s\n",p->name);
                sem_post(p
->left);
                sem_post(p
->right);
                sleep(
1);

            } 

else {
                sem_post(p
->left);
            }
        }
        
if (p->is_stop == 1) {
            
break;
        }
    }
    pthread_exit(NULL);
}