日期:2014-05-16 浏览次数:20767 次
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int sum = 0;
void *thread1(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
sum++;
printf("thread1--->%d\n",sum);
sleep(3);
pthread_mutex_unlock(&mutex);
printf("thread1--->\n");
printf("thread1--->\n");
printf("thread1--->\n");
printf("thread1--->\n");
printf("thread1--->\n");
printf("thread1--->\n");
sleep(1); /*只有开启睡眠才可以让trylock获得锁*/
}
}
void *thread2(void *arg)
{
printf("start thread2....\n");
while(1)
{
int rel = pthread_mutex_trylock(&mutex);
if(0 == rel)
{
sum--;
printf("thread2-->%d\n",sum);
pthread_mutex_unlock(&mutex);
}
}
}
int main()
{
printf("test\n");
sleep(1);
pthread_t thid1, thid2;
printf("condition variable study!\n");
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&thid1, NULL, (void *) thread1, NULL);
pthread_create(&thid2, NULL, (void *) thread2, NULL);
pthread_join(thid1,NULL);
pthread_join(thid2,NULL);
return 0;
}