《Linux操作系统》课程报告 第32页
{
while(x>0) {
pthread_mutex_lock(&mutex); printf(\ 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 (\
//如果初始化失败,打印错误信息
exit (1); //并退出 }
x=10;//对全局变量赋初值
ret = pthread_create(&id1, NULL, (void *)&thread1, NULL);
if(ret != 0)//创建线程1 {
printf (\ exit (1); }
ret = pthread_create(&id2, NULL, (void *)&thread2, NULL);
if(ret != 0)
{ //创造线程2 printf (\ exit (1); }
pthread_join(id1, NULL); //线程合并 pthread_join(id2, NULL); return (0); }
(2)实验结果截图
《Linux操作系统》课程报告 第33页
可以看到两个线程互斥使用全局变量x,并且是交替使用的,线程1先使用全局变量x,线程2再使用全局变量x,当全局变量归于0时,两个线程将结束,主线程运行至退出。 4.2.2线程的同步——读写锁
(1)源代码
/* *
*读写锁
* 只要没有进程持有某个给定的读写锁用于写,那么任意数目的 *线程都可持有该读写锁用于读
* 仅当没有线程持有某个给定的读写锁用于读或写,才能分配该 *读写锁用于写。 */
#include
int product = 0; //定义全局变量
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
//静态初始化读写锁
void * threadRead(void * arg) //线程函数读 {
int cnt = 0;
while(cnt++ < 10) {
pthread_rwlock_rdlock(&rwlock); //读锁
printf(\
pthread_rwlock_unlock(&rwlock); //解锁 sleep(1); }
《Linux操作系统》课程报告 第34页
}
void * tidProduce(void * arg) //线程函数写 加1 {
int cnt = 0;
while(cnt++ < 10) {
pthread_rwlock_wrlock(&rwlock); //写锁
product++;
printf(\
pthread_rwlock_unlock(&rwlock); //解锁 sleep(1); } }
void * threadConsume(void * arg) //线程函数写 减1 {
int cnt = 0;
while(cnt++ < 10) {
pthread_rwlock_wrlock(&rwlock); //写锁
product--;
printf(\
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(\ exit(0); } }
《Linux操作系统》课程报告 第35页
if(pthread_create(&tidproduce, NULL, tidProduce, NULL)) {
printf(\ exit(0); }
if(pthread_create(&tidconsume, NULL, threadConsume,
NULL)) {
printf(\ exit(0); }
pthread_exit(NULL); //等待所有线程结束
return 0; }
(2)实验结果截图
我们在这里定义的阈值是10,并且生产和消费的功能交替进行,阅读者会阅读出当前的产品数目,因为这里定义了两个阅读者,则两个阅读者会同时读到产品的数目,而由于生产
相关推荐: