zoukankan      html  css  js  c++  java
  • [线程同步问题]读者写者同步问题

    问题描述

    有读者和写者两组并发进程,共享一个文件,当两个或以上的读进程同时访问共享数据时不会产生副作用,但若某个写进程和其他进程(读进程或写进程)同时访问共享数据时则可能导致数据不一致的错误。因此要求:

    ①允许多个读者可以同时对文件执行读操作;

    ②只允许一个写者往文件中写信息;

    ③任一写者在完成写操作之前不允许其他读者或写者工作;

    ④写者执行写操作前,应让已有的读者和写者全部退出。

    问题分析

    1) 关系分析。由题目分析读者和写者是互斥的,写者和写者也是互斥的,而读者和读者不存在互斥问题。

    2) 整理思路。两个进程,即读者和写者。写者是比较简单的,它和任何进程互斥,用互斥信号量的P操作、V操作即可解决。读者的问题比较复杂,它必须实现与写者互斥的同时还要实现与其他读者的同步,因此,仅仅简单的一对P操作、V操作是无法解决的。那么,在这里用到了一个计数器,用它来判断当前是否有读者读文件。当有读者的时候写者是无法写文件的,此时读者会一直占用文件,当没有读者的时候写者才可以写文件。同时这里不同读者对计数器的访问也应该是互斥的。

    3) 信号量设置。首先设置信号量count为计数器,用来记录当前读者数量,初值为0; 设置mutex为互斥信号量,用于保护更新count变量时的互斥;设置互斥信号量rw用于保证读者和写者的互斥访问。

    伪代码实现:

    int count=0;  //用于记录当前的读者数量
    semaphore mutex=1;  //用于保护更新count变量时的互斥
    semaphore rw=1;  //用于保证读者和写者互斥地访问文件
    writer () 
    {  //写者进程
        while (true)
    	{
            P(rw); // 互斥访问共享文件
            Writing;  //写入
            V(rw) ;  //释放共享文件
        }
    }
    reader () 
    {  // 读者进程
        while(true)
    	{
            P (mutex) ;  //互斥访问count变量
            if (count==0)  //当第一个读进程读共享文件时
                P(rw);  //阻止写进程写
            count++;  //读者计数器加1
            V (mutex) ;  //释放互斥变量count
            reading;  //读取
            P (mutex) ;  //互斥访问count变量
            count--; //读者计数器减1
            if (count==0)  //当最后一个读进程读完共享文件
                V(rw) ;  //允许写进程写
            V (mutex) ;  //释放互斥变量 count
        }
    }
    

    在Windows下代码实现:读者互斥访问count用关键段,读者、写者互斥用事件完成。

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <process.h>
    #include <windows.h>
    
    const int writter_num = 2;
    const int reader_sum = 8;
    int reader_count;
    
    HANDLE g_hEvent;
    CRITICAL_SECTION g_csThreadCode;
    
    unsigned int __stdcall writter_thread(void *param)
    {
    	printf("	写线程等待...
    ");
    	WaitForSingleObject(g_hEvent, INFINITE);
    
    	printf("	写线程开始写文件...
    ");
    	Sleep(rand() % 100);
    	printf("	写线程结束写文件
    ");
    
    	SetEvent(g_hEvent);
    
    	return 0;
    }
    unsigned int __stdcall reader_thread(void *param)
    {
    	EnterCriticalSection(&g_csThreadCode);
    	if(reader_count == 0)
    		WaitForSingleObject(g_hEvent, INFINITE);
    	reader_count++;
    	LeaveCriticalSection(&g_csThreadCode);
    
    	printf("读线程%d开始读文件...
    ", GetCurrentThreadId());
    	Sleep(rand() % 100);
    	printf("读线程%d结束读文件
    ", GetCurrentThreadId());
    
    	EnterCriticalSection(&g_csThreadCode);
    	reader_count--;
    	if (reader_count == 0)
    		SetEvent(g_hEvent);
    	LeaveCriticalSection(&g_csThreadCode);
    
    	return 0;
    }
    
    int main()
    {
    	//设置一个随机种子
    	srand((unsigned)time(NULL));
    	InitializeCriticalSection(&g_csThreadCode);
    	g_hEvent = CreateEvent(NULL, false, true, NULL);
    	//再读读者数目
    	reader_count = 0;
    	int i,j;
    
    	HANDLE handle[reader_sum + writter_num];
    	for (i = 0; i < reader_sum; i++)
    	{
    		handle[i] = (HANDLE)_beginthreadex(NULL, 0, reader_thread, NULL, 0, NULL);
    	}
    	for (j = i; j < reader_sum + writter_num; j++)
    	{
    		handle[j] = (HANDLE)_beginthreadex(NULL, 0, writter_thread, NULL, 0, NULL);
    	}
    	
    
    	WaitForMultipleObjects(reader_sum + writter_num, handle, true, INFINITE);
    
    	DeleteCriticalSection(&g_csThreadCode);
    	CloseHandle(g_hEvent);
    	for(i = 0; i < reader_sum + 1; i++)
    	{
    		CloseHandle(handle[i]);
    	}
    
    
    	return 0;
    }
    

    执行结果:

    从执行结果可以看出,在上面的算法中,读进程是优先的,也就是说,当存在读进程时,写操作将被延迟,并且只要有一个读进程活跃,随后而来的读进程都将被允许访问文件。这样的方式下,会导致写进程可能长时间等待,且存在写进程“饿死”的情况。


     如果希望写进程优先,即当有读进程正在读共享文件时,有写进程请求访问,这时应禁止后续读进程的请求,等待到已在共享文件的读进程执行完毕则立即让写进程执行,只有在无写进程执行的情况下才允许读进程再次运行。为此,增加一个信号量并且在上面的程序中 writer()和reader()函数中各增加一对PV操作,就可以得到写进程优先的解决程序。

    伪代码实现:

    int count = 0;  //用于记录当前的读者数量
    semaphore mutex = 1;  //用于保护更新count变量时的互斥
    semaphore rw=1;  //用于保证读者和写者互斥地访问文件
    semaphore w=1;  //用于实现“写优先”
    writer()
    {
        while(1)
    	{
            P(w);  //在无写进程请求时进入
            P(rw);  //互斥访问共享文件
            writing;  //写入
            V(rw);  // 释放共享文件
            V(w) ;  //恢复对共享支件的访问
        }
    }
    reader () 
    {  //读者进程
        while (1)
    	{
            P (w) ;  // 在无写进程请求时进入
            P (mutex);  // 互斥访问count变量
            if (count==0)  //当第一个读进程读共享文件时
                P(rw);  //阻止写进程写
            count++;  //读者计数器加1
            V (mutex) ;  //释放互斥变量count
            V(w);  //恢复对共享文件的访问
            reading;  //读取
            P (mutex) ; //互斥访问count变量
            count--;  //读者计数器减1
            if (count==0)  //当最后一个读进程读完共享文件
                V(rw);  //允许写进程写
            V (mutex);  //释放互斥变量count
        }
    }
    

    windows代码实现:

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <process.h>
    #include <windows.h>
    
    //定义读者和写者的数量
    const int WRITER_NUM = 2;
    const int READER_NUM = 8;
    
    //读者当前的数量
    int g_reader_count;
    
    //同步变量或者内核对象
    CRITICAL_SECTION g_hThreadCode;
    HANDLE g_hEventrw;
    HANDLE g_hEventw;
    
    unsigned int __stdcall reader_thread(void *param)
    {
    	WaitForSingleObject(g_hEventw, INFINITE);
    	EnterCriticalSection(&g_hThreadCode);
    	if (g_reader_count == 0)
    	{
    		WaitForSingleObject(g_hEventrw, INFINITE);
    	}
    	g_reader_count++;
    	LeaveCriticalSection(&g_hThreadCode);
    	SetEvent(g_hEventw);
    
    	printf("%d线程开始读文件
    ", GetCurrentThreadId());
    	Sleep(rand() % 100);
    	printf("%d线程结束读文件
    ", GetCurrentThreadId());
    
    	EnterCriticalSection(&g_hThreadCode);
    	g_reader_count--;
    	if (g_reader_count == 0)
    	{
    		SetEvent(g_hEventrw);
    	}
    	LeaveCriticalSection(&g_hThreadCode);
    
    	return 0;
    }
    
    unsigned int __stdcall writer_thread(void *param)
    {
    	WaitForSingleObject(g_hEventw, INFINITE);
    	WaitForSingleObject(g_hEventrw, INFINITE);
    
    	printf("	%d线程开始写文件
    ", GetCurrentThreadId());
    	Sleep(rand() % 100);
    	printf("	%d线程结束文写文件
    ", GetCurrentThreadId());
    
    	SetEvent(g_hEventrw);
    	SetEvent(g_hEventw);
    
    	return 0;
    }
    
    int main()
    {
    	//初始化工作
    	InitializeCriticalSection(&g_hThreadCode);
    	g_hEventrw = CreateEvent(NULL, false, true, NULL);
    	g_hEventw  = CreateEvent(NULL, false, true, NULL);
    	g_reader_count = 0;
    	//设置随机种子
    	srand((unsigned int)time(NULL));
    
    	int i,j;
    
    	HANDLE handle[WRITER_NUM + READER_NUM];
    	for (i = 0; i < WRITER_NUM; i++)
    	{
    		handle[i] = (HANDLE)_beginthreadex(NULL, 0, writer_thread, NULL, 0, NULL);
    	}
    	for (j = i; j < WRITER_NUM + READER_NUM; j++)
    	{
    		handle[j] = (HANDLE)_beginthreadex(NULL, 0, reader_thread, NULL, 0, NULL);
    	}
    
    	WaitForMultipleObjects(WRITER_NUM + READER_NUM, handle, true, INFINITE);
    
    	//释放资源
    	DeleteCriticalSection(&g_hThreadCode);
    	CloseHandle(g_hEventw);
    	CloseHandle(g_hEventrw);
    	for (i  = 0; i < WRITER_NUM + READER_NUM; i++)
    	{
    		CloseHandle(handle[i]);
    	}
    
    	return 0;
    }
    

    执行结果:

    现在的写者线程就不会出现饿死的现象了。  

  • 相关阅读:
    java服务端微信小程序支付
    H5商城,纯前端静态页面
    上海期货交易所CTP行情和交易接入
    iOS12 Network框架 自签名证书认证
    Android 本地播放器
    Spring Boot 集成 GRPC
    pandas DataFrame 索引(iloc 与 loc 的区别)
    编程规范 —— 类的命名
    pandas 操作 excel
    matplotlib 操作子图(subplot,axes)
  • 原文地址:https://www.cnblogs.com/stemon/p/4858548.html
Copyright © 2011-2022 走看看