代码如下,期望效果是四个线程按顺序循环打印0123,但是实际总是死锁,一个循环0123都打不完,实在是搞不懂为什么会死锁
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define NUM 4
pthread_mutex_t mutex;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static int num = 0;
static int next(int i)
{
if(i == 3)
return 0;
return i+1;
}
static void *handler(void *p)
{
int i = *(int*)p;
while(1)
{
while(num != i)
pthread_cond_wait(&cond, &mutex);
//printf("thread %d\n", i);
pthread_mutex_lock(&mutex);
printf("%d\n", num);
//fflush(NULL);
num = next(num);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
pthread_exit(p);
}
int main()
{
int i = 0;
pthread_t tid[NUM];
void *ptr = NULL;
pthread_mutex_init(&mutex, NULL);
pthread_mutex_lock(&mutex);
for(; i < NUM; i++)
{
int *num = malloc(sizeof(int));
*num = i;
if(pthread_create(tid+i, NULL, handler, (void*)num))
{
perror("pthread_create()");
exit(-1);
}
}
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
//alarm(1);
for(i = 0; i < NUM; i++)
{
pthread_join(tid[i], ptr);
free(ptr);
}
exit(0);
}
```