下面给出的 Pthread 程序演示了 pthread 中的互斥锁示例。但是,在运行此代码时,大多数情况下都会发生死锁,从而为某些运行提供正确的结果。
#include<pthread.h>
#include<stdio.h>
#include<unistd.h>
volatile int sv=10;
volatile int x,y,temp=10;
pthread_mutex_t mut;
pthread_cond_t con;
void *ChildThread(void *arg)
{
pthread_mutex_lock (&mut);
pthread_cond_wait(&con, &mut);
x=sv;
x++;
sv=x;
printf("The child sv is %d\n",sv);
pthread_mutex_unlock (&mut);
pthread_exit(NULL);
}
void *ChildThread2(void *arg)
{
pthread_mutex_lock (&mut);
y=sv;
y--;
sv=y;
printf("The child2 sv is %d\n",sv);
pthread_cond_signal(&con);
pthread_mutex_unlock (&mut);
pthread_exit(NULL);
}
int main(void)
{
pthread_t child1,child2,child3;
pthread_mutex_init(&mut, NULL);
pthread_create(&child2,NULL,ChildThread2,NULL);
pthread_create(&child1,NULL,ChildThread,NULL);
pthread_cond_destroy(&con);
pthread_mutex_destroy(&mut);
pthread_join(child1,NULL);
pthread_join(child2,NULL);
return 0;
}