linux 利用互斥锁解决五哲学家问题

编程入门 行业动态 更新时间:2024-10-07 00:21:22

linux 利用互斥锁解决五<a href=https://www.elefans.com/category/jswz/34/1769411.html style=哲学家问题"/>

linux 利用互斥锁解决五哲学家问题

分享一段自己写的在Linux系统下使用互斥锁模拟解决五哲学家进餐问题的代码,编译时记得加参数: -lpthread -std=c99
// 因为课程原因又重新调整一下代码,但使用老网站编辑器时多了一些乱码,不知道怎么回事


#include <stdio.h>
#include <stdlib.h>
#include <time.h>#include <unistd.h>
#include <sys/syscall.h>
#include "pthread.h"#define NUM_MAX 5
#define NUM 6
struct prodcons 
{int num;int test;pthread_mutex_t lock;	pthread_cond_t notuse;
};void init (struct prodcons *prod);
int lock (struct prodcons *prod);
void unlock (struct prodcons *prod);
void *philosopher (int n);
//void manager (void *data);struct prodcons buffer[NUM];
struct prodcons *r;int main (int argc,char *argv[])
{pthread_t th_1,th_2,th_3,th_4,th_5,th_m;void *retval;for (int c=0;c<NUM;c++){init(&buffer[c]);}pthread_create (&th_1, NULL, philosopher, 1);pthread_create (&th_2, NULL, philosopher, 2);pthread_create (&th_3, NULL, philosopher, 3);pthread_create (&th_4, NULL, philosopher, 4);pthread_create (&th_5, NULL, philosopher, 5);
//	pthread_create (&th_m, NULL, manager, 0);pthread_join (th_1, &retval);pthread_join (th_2, &retval);pthread_join (th_3, &retval);pthread_join (th_4, &retval);pthread_join (th_5, &retval);return 0;
}void init (struct prodcons *prod)
{pthread_mutex_init (&prod->lock,NULL);pthread_cond_init (&prod->notuse,NULL);}int lock (struct prodcons *prod)
{return pthread_mutex_lock(&prod->lock);
//	prod->test=2;
//	printf("%d\n",prod->test);
//	while(!(pthread_cond_wait(&prod->notuse,NULL)));}
void unlock (struct prodcons *prod)
{pthread_mutex_unlock(&prod->lock);}
void *philosopher(int n)
{if (n == NUM_MAX){while(1){int h=1,g=1;while (1){h = lock(&buffer[0]);g = lock(&buffer[n-1]);if (g){unlock(&buffer[n-1]);printf("not get two together,put one\n");}if (h){unlock(&buffer[0]);printf("not get two together,put one\n");}if(h == 0 && g == 0) {printf("P%d get two.\n",n);break;}}printf("P%d is eating.\n",n);sleep(1);unlock(&buffer[0]);unlock(&buffer[n-1]);printf("P%d is thinking.\n",n);sleep(1);}return NULL;		}else{while(1){int h=1,g=1;while (1){h = lock(&buffer[n]);g = lock(&buffer[n-1]);if (g){unlock(&buffer[n]);printf("not get two together,put one\n");}if (h){unlock(&buffer[n-1]);printf("not get two together,put one\n");}if(h == 0 && g == 0) {printf("P%d get two.\n",n);break;}}printf("P%d is eating.\n",n);sleep(1);unlock(&buffer[n]);unlock(&buffer[n-1]);printf("P%d is thinking.\n",n);sleep(1);}return NULL;}	
}
/*
void manager (void *data)
{for (int z=0;z<5;z++){for (r=buffer;r<buffer+5;r++){pthread_cond_signal(&buffer->notuse);}sleep(3);}
} 
*/






更多推荐

linux 利用互斥锁解决五哲学家问题

本文发布于:2024-02-28 11:01:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1769483.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:哲学家   互斥   linux

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!