- 论坛徽章:
- 0
|
每人按序取得1根筷子,这时筷子已经取完,其中任何一个人再想取得筷子,这时已经没有筷子了,这个时候就死锁了吧。代码我随便写的(RedHat下测试通过):
- #include <unistd.h>
- #include <pthread.h>
- #include <sys/types.h>
- #include <errno.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <semaphore.h>
- pthread_mutex_t dinner_lock = PTHREAD_MUTEX_INITIALIZER;
- pthread_cond_t dinner_cond = PTHREAD_COND_INITIALIZER;
- int order = 0;
- sem_t dinner_sem;
- void *dinner_proc(void *param)
- {
- int index = *(int *)param;
-
- printf("enter %d thread\n", index);
-
- pthread_detach(pthread_self()); /* reclaim by itself */
-
- pthread_mutex_lock(&dinner_lock);
-
- while (order == index)
- pthread_cond_wait(&dinner_cond, &dinner_lock);
-
- sem_wait(&dinner_sem); /* get a chopstick */
- printf("%d got the first chopstick\n", index);
-
- pthread_mutex_unlock(&dinner_lock);
-
- ++order;
- pthread_cond_signal(&dinner_cond);
-
- sleep(1);
- // printf("ready to get second chopstick..\n");
-
- sem_wait(&dinner_sem); /* dead lock */
- printf("%d got second chopstick..\n", index);
-
- sleep(3);
- printf("eat dinner...\n");
-
- sem_post(&dinner_sem);
-
- pthread_exit(0);
- }
- int main(void)
- {
- int i = 0;
- pthread_t tid;
-
- if (sem_init(&dinner_sem, 0, 5) < 0) /* 5 chopsticks initilized */
- {
- fprintf(stderr, "sem_init error: %s\n", strerror(errno));
- exit(-1);
- }
-
- for (i = 0; i < 5; ++i)
- {
- int *pindex;
-
- // printf("create %d thread\n", i);
- pindex = (int *)malloc(sizeof(int));
- *pindex = i;
- if (pthread_create(&tid, NULL, dinner_proc, (void *)pindex) < 0)
- {
- fprintf(stderr, "pthread_create[%d] error: %s\n", (i+1), strerror(errno));
- exit(-1);
- }
- }
-
- ++order;
- pthread_cond_signal(&dinner_cond);
-
- pause();
-
- return 0;
- }
复制代码 |
|