/*
* 线程同步——互斥量
* 创建两个线程,使用互斥量使任一时刻只有一个线程对全局变量进行
操作
* Lzy 2011-6-19
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t mutex; /* 定义
互斥量 */
int x;
/* 定义全局变量 */
void thread1(void) /* 定义线程1运
行的函数,其功能是对全局变量x进行逐减操作 */
{
while(x>0)
{
pthread_mutex_lock(&mutex); /* 对互斥量进行
加锁操作 */
printf("Thread 1 is running : x=%d
",x);
x--;
pthread_mutex_unlock(&mutex); /* 对互斥量进行
解锁操作 */
sleep(1);
}
pthread_exit(NULL);
}
void thread2(void) /* 定义线程2运
行的函数,功能与thread2相同 */
{
while(x>0)
{
pthread_mutex_lock(&mutex); /* 对互斥量进行
加锁操作 */
printf("Thread 2 is running : x=%d
",x);
x--;
pthread_mutex_unlock(&mutex); /* 对互斥量进行
解锁操作 */
sleep(1);
}
pthread_exit(NULL);
}
int main(void)
{
pthread_t id1,id2;
/* 定义线程的标识符 */
int ret;
ret = pthread_mutex_init(&mutex,NULL); /* 对互斥量进行
初始化,这里使用默认的属性 */
if(ret != 0)
{
printf ("Mutex initialization failed.
"); /* 如果
初始化失败,打印错误信息 */
exit (1);
}
x=10;
/* 对全局变量赋初值 */
ret = pthread_create(&id1, NULL, (void *)&thread1, NULL);
/* 创建线程1 */
if(ret != 0)
{
printf ("Thread1 creation failed.
");
exit (1);
}
ret = pthread_create(&id2, NULL, (void *)&thread2, NULL);
/* 创建线程2 */
if(ret != 0)
{
printf ("Thread2 creation failed.
");
exit (1);
}
pthread_join(id1, NULL); /*线程
合并 */
pthread_join(id2, NULL);
return (0);
}
/*
* 线程同步
* ——读写锁
* 只要没有进程持有某个给定的读写锁用于写,那么任意数目的
线程都可持有该读写锁用于读
* 仅当没有线程持有某个给定的读写锁用于读或写,才能分配该
读写锁用于写。
* Lzy 2011-6-19
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int product = 0; //定义全局变量
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER; //静态
初始化读写锁
void * threadRead(void * arg) //线程函数读
{
int cnt = 0;
while(cnt++ < 100)
{
pthread_rwlock_rdlock(&rwlock); //读锁
printf("Read: product = %d
", product);
pthread_rwlock_unlock(&rwlock); //解锁
sleep(1);
}
}
void * tidProduce(void * arg) //线程函数写 加1
{
int cnt = 0;
while(cnt++ < 100)
{
pthread_rwlock_wrlock(&rwlock); //写锁
product++;
printf("Produce: product = %d
", product);
pthread_rwlock_unlock(&rwlock); //解锁
sleep(1);
}
}
void * threadConsume(void * arg) //线程函数写 减1
{
int cnt = 0;
while(cnt++ < 100)
{
pthread_rwlock_wrlock(&rwlock); //写锁
product--;
printf("Consume: product = %d
", product);
pthread_rwlock_unlock(&rwlock); //解锁
sleep(2);
}
}
int main(void)
{
int i;
pthread_t tid[10], tidconsume, tidproduce;
for(i = 0; i < 2; i++)
{
if(pthread_create(&tid[i], NULL, threadRead,
NULL))
{
printf("pthread_create error
");
exit(0);
}
}
if(pthread_create(&tidproduce, NULL, tidProduce, NULL))
{
printf("pthread_create error
");
exit(0);
}
if(pthread_create(&tidconsume, NULL, threadConsume,
NULL))
{
printf("pthread_create error
");
exit(0);
}
pthread_exit(NULL); //等待所有线程结束
return 0;
}