- 论坛徽章:
- 0
|
下面是个多线程同步的简单模型在LINUX下的代码,但有错误,会出现死锁!哪位高手
能帮我解决?!谢谢!
#include <stdio.h>;
#include <pthread.h>;
#include <errno.h>;
static int count = 0;
static pthread_mutex_t countlock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t bcond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t bmutex = PTHREAD_MUTEX_INITIALIZER;
static int reach = 0;
static int limit = 4;
int increment(void) { /* increment the counter */
int error;
if (error = pthread_mutex_lock(&countlock))
return error;
count++;
return pthread_mutex_unlock(&countlock);
}
int decrement(void) { /* decrement the counter */
int error;
if (error = pthread_mutex_lock(&countlock))
return error;
count--;
return pthread_mutex_unlock(&countlock);
}
int getcount(int *countp) { /* retrieve the counter */
int error;
if (error = pthread_mutex_lock(&countlock))
return error;
*countp = count;
return pthread_mutex_unlock(&countlock);
}
int waitbarrier(void) { /* wait at the barrier until all n threads arrive */
int berror = 0;
int error;
if (error = pthread_mutex_lock(&bmutex)) /* couldn't lock, give up */
return error;
if (limit <= 0) { /* make sure barrier initialized */
pthread_mutex_unlock(&bmutex);
return EINVAL;
}
reached++;
while ((reached < limit) && !berror)
berror = pthread_cond_wait(&bcond, &bmutex);
if (!berror)
berror = pthread_cond_broadcast(&bcond); /* wake up everyone */
reached = 0;/*how to reset reached?*/
error = pthread_mutex_unlock(&bmutex);
if (berror)
return berror;
return error;
}
void do_work()
{
int i = 0, val;
while (i < 4) {
increment();
getcount(&val);
printf("%d\n", val);
decrement();
waitbarrier();
}
}
int main(int argc, char *argv[])
{
int i, *status;
pthread_t thread_id[4];
for (i = 0; i < 4; i++) {
if (pthread_create(&thread_id, NULL, (void* (*)(void *))do_work, (void*)NULL ) >; 0) {
fprintf(stderr, "pthread_create failure\n" ;
exit( -1 );
}
}
for (i = 0; i < 4; i++) {
if (pthread_join(thread_id, (void **)status) >; 0) {
fprintf(stderr, "pthread_join failure\n" ;
exit( -1 );
}
}
return 0;
} |
|