#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM 5
pthread_mutex_t lock[NUM] = {PTHREAD_MUTEX_INITIALIZER};
void *thread_proc(void *p)
{
int pos = (int)p;
int right = pos;
int left = ((pos - 1) < 0) ?NUM-1:pos-1;
while(1)
{
printf("person %c want to eat now, waiting the order....\n",65+pos);
pthread_mutex_lock(&lock[left]);
printf("person %c get the left %d\n",65+pos,left);
pthread_mutex_lock(&lock[right]);
int n = rand() % 10;
printf("person %c get the right %d, now start eatting %d seconds.....\n",65+pos,right,n);
sleep(rand()%10);
printf("person %c eat done! put down the %d and %d ...\n",65+pos,left,right);
pthread_mutex_unlock(&lock[right]);
pthread_mutex_unlock(&lock[left]);
n = rand() % 10;
printf("person %c now is sleeping %d seconds....\n",65+pos,n);
sleep(rand()%10);
}
return NULL;
}
int main()
{
pthread_t pid[NUM];
int i;
srand(time(NULL));
for (i = 0; i < NUM; i++)
{
pthread_create(&pid[i],NULL,thread_proc,(void*)i);
}
for (i = 0; i < NUM; i++)
{
pthread_join(pid[i],NULL);
}
return 0;
}
dijkstra 算法
最新推荐文章于 2019-02-12 23:19:05 发布