How to synchronize access to a shared resource in a multithreading environment by using Visual C#

C++Builder 6实战精解:经典RAD工具在现代开发中的价值与应用 快速应用程序开发(RAD)是一种通过可视化设计和组件复用提升开发效率的编程范式,其核心原理在于将界面元素封装为可拖拽的控件,并通过事件驱动模型响应用户交互。这种技术价值在于能大幅缩短GUI应用的开发周期,降低界面编码的复杂度。在桌面工具、数据采集和工业控制等对执行效率和Windows原生集成度要求较高的应用场景中,RAD工具依然具有独特优势。C++Builder 6作为经典的RAD环境,其VCL框架和可视化设计器深刻体现了这一理念。通过剖析其数据感知控件和消息机制,开发者不仅能维护遗留系统,更能理解模块化设 阅读详情

来自:

http://support.microsoft.com/default.aspx?scid=kb;en-us;816161

You can perform multiple tasks in Microsoft Visual C# applications at the same time by using multithreading. Multithreading can start different threads   to complete different tasks at the same time. Multithreading also improves the performance and   responsiveness of your applications.

Because multiple threads can   access a resource at the same time, you may want to synchronize individual   threads with other parts of your program. This article describes some common   scenarios with multithreading programming, and explains how to synchronize the   access to a shared resource among the multiple threads.

Help to Protect Your Global Data in Modules in a Multithreaded Environment

The public fields in methods are accessible to all the threads in   your application. To synchronize the access to the public fields, you can use   property instead of field, and use a ReaderWriterLock object to control the access. To do this, follow these steps:  
  1. Start Microsoft Visual Studio.
  2. On the File menu, point to New, and then click Project.
  3. Click Visual C# Projects under Project Types, and then click Console Application under Templates.

    Note In Visual Studio 2005 or in Visual Studio 2008, click Visual C# under Project Types, and then click Console Application under Templates.
  4. In the Name text box, type MultiThreadApplication, and then click OK.
  5. Replace the existing code with the following code in Class1.cs.

    Note In Visual Studio 2005 and in Visual Studio 2008, the default file is Program.cs.
    using System;
    using System.Threading;
    
    namespace MultiThreadApplication
    {
    	class Class1
    	{
    		private ReaderWriterLock rwl = new ReaderWriterLock();
    		private long myNumber;
    		public long Number   // the Number property
    		{
    			get
    			{
    				//Acquire a read lock on the resource.
    				rwl.AcquireReaderLock(Timeout.Infinite);                
    				try
    				{
    					Console.WriteLine("Thread:{0} starts getting the Number", Thread.CurrentThread.GetHashCode());
    					Thread.Sleep(50);
    					Console.WriteLine("Thread:{0} got the Number", Thread.CurrentThread.GetHashCode());
    
    				}
    				finally
    				{
    					//Release the lock.
    					rwl.ReleaseReaderLock();
    				}
    				return myNumber;
    			}
    			set
    			{
    				//Acquire a write lock on the resource.
    				rwl.AcquireWriterLock(Timeout.Infinite);
    				try
    				{
    					Console.WriteLine("Thread: {0} start writing the Number", Thread.CurrentThread.GetHashCode());
    					Thread.Sleep(50);
    					myNumber = value;
    					Console.WriteLine("Thread: {0} written the Number", Thread.CurrentThread.GetHashCode());
    				}
    				finally
    				{
    					//Release the lock.
    					rwl.ReleaseWriterLock();
    				}
    			}
    		}
    		
    		[STAThread]
    		static void Main(string[] args)
    		{
    			Thread []threadArray = new Thread[20]; 
    			int threadNum;
    
    
    			Class1 Myclass = new Class1();
    			ThreadStart myThreadStart = new ThreadStart(Myclass.AccessGlobalResource);
    
    			//Create 20 threads.
    			for( threadNum = 0; threadNum < 20; threadNum++)
    			{
    				threadArray[threadNum] = new Thread(myThreadStart);
    			}
    
    			//Start the threads.
    			for( threadNum = 0; threadNum < 20; threadNum++)
    			{   
    				threadArray[threadNum].Start();
    			}
    
    			//Wait until all the thread spawn out finish.
    			for( threadNum = 0; threadNum < 20; threadNum++)
    				threadArray[threadNum].Join();
    
    			Console.WriteLine("All operations have completed. Press enter to exit");
    			Console.ReadLine();
    		}
    
    		public void AccessGlobalResource()
    		{
    			Random rnd = new Random();
    			long theNumber;
    			
    			if (rnd.Next() % 2 != 0)
    				theNumber = Number;
    			else
    			{
    				theNumber = rnd.Next();
    				Number = theNumber;
    			}
    
    		}
    	}
    }
    
  6. Build the project, and then run the application.

Help to Make Your Class Thread-Safe

Multiple threads may try to access an object at the same   time. When more than one thread competes for access to an   object at the same time, some threads may receive an invalid state if another   thread modifies the resource at the same time. For example, if a thread   reads the field of the object while another thread is modifying the field,   the first thread may receive an invalid state of the field. This situation is   named a race condition.

To avoid this situation, you can help to protect   critical sections of your code from race conditions by using locks. A lock,   represented by the Visual C# keyword lock Statement, allows a single thread of   execution to obtain exclusive execution rights on an object. The following   example steps demonstrate locks:  
  1. Open Visual Studio.
  2. On the File menu, point to New, and then click Project.
  3. Click Visual C# Projects under Project Types, and then click Console Application under Templates.

    Note In Visual Studio 2005 or in Visual Studio 2008, click Visual C# under Project Types, and then click Console Application under Templates.
  4. In the Name text box, type MultiThreadLockApplication, and then click OK.
  5. Replace the existing code with the following code in Class1.cs:
    using System;
    using System.Threading;
    
    namespace MultiThreadLockApplication
    {
    	class Student
    	{
    		private static string myTeacherName = "Bill";
    		private string myName = "Grace";
    		private static object somePrivateStaticObject = new Object();
    
    		public static string TeacherName
    		{
    			get
    			{
    				string theName;
    
    				// Synchronize access to the shared member.
    				lock(somePrivateStaticObject)
    				{
    					Console.WriteLine("Thread {0} starts to get the teacher's name",Thread.CurrentThread.GetHashCode());
    					theName = myTeacherName;
    
    					// Wait for 0.3 second.
    					Thread.Sleep(300);
    					Console.WriteLine("Thread {0} finished to get the teacher's name:{1}.", Thread.CurrentThread.GetHashCode(), theName);
    				}
    				return theName;
    			}
    
    			set
    			{
    				lock(somePrivateStaticObject)
    				{
    					Console.WriteLine("Thread {0} starts to set the teacher's name.", Thread.CurrentThread.GetHashCode());
    					myTeacherName = value;
    
    					// Wait for 0.3 second.
    					Thread.Sleep(300);
    					Console.WriteLine("Thread {0} finished to set the teacher's name:{1}.", Thread.CurrentThread.GetHashCode(), value);
    				}
    			}
    		}
    
    		public string GetName()
    		{
    			string theName;
    			lock(this)
    			{
    				Console.WriteLine("Thread {0} starts to get the student's name.", Thread.CurrentThread.GetHashCode());
    				theName = myName;
    
    				// Wait for 0.3 second.
    				Thread.Sleep(300);
    				Console.WriteLine("Thread {0} finished to get the student's name:{1}", Thread.CurrentThread.GetHashCode(), theName);
    				return theName;
    			}
    		}
    
    		public string SetName(string NewName)
    		{
    			string theOldName;
    			lock(this)
    			{
    				Console.WriteLine("Thread {0} starts to set the student's name.", Thread.CurrentThread.GetHashCode());
    				theOldName = myName;
    				myName = NewName;
    
    				// Wait for 0.3 second.
    				Thread.Sleep(300);
    				Console.WriteLine("Thread {0} finished to set the student's name:{1}", Thread.CurrentThread.GetHashCode(), NewName);
    			}
    			return theOldName;
    		}
    	}
    
    	class Class1
    	{
    		public static int WorkItemNum = 20;
    		public static AutoResetEvent Done = new AutoResetEvent(false);
    
    		public static void AccessClassResource(object state)
    		{
    			Random rnd = new Random();
    			string theName;
    			Student AStudent = (Student) state;
    
    			if( (rnd.Next() %2) != 0)
    			{
    				if( (rnd.Next() %2) != 0)
    				{
    					switch (rnd.Next() %3 )
    					{
    						case 0:
    							Student.TeacherName = "Tom";
    							break;
    						case 1:
    							Student.TeacherName = "Mike";
    							break;
    						case 2:
    							Student.TeacherName = "John";
    							break;
    					}
    				}
    				else
    				{
    					theName = Student.TeacherName;
    				}
    			}
    			else
    			{
    				if( (rnd.Next() %2) != 0)
    				{
    					switch (rnd.Next() %3 )
    					{
    						case 0:
    							AStudent.SetName("Janet");
    							break;
    						case 1:
    							AStudent.SetName("David");
    							break;
    						case 2:
    							AStudent.SetName("Ben");
    							break;
    					}
    				}
    				else
    				{
    					theName = AStudent.GetName();
    				}
    			}
    
    			if(Interlocked.Decrement( ref WorkItemNum) == 0)
    			{
    				Done.Set();
    			}
    		}
    
    		[STAThread]
    		static void Main(string[] args)
    		{
    			int threadNum;
    			Student AStudent = new Student();
    
    			// Queue up 20 work items in the ThreadPool.
    			for (threadNum = 0 ; threadNum <= WorkItemNum -1 ; threadNum++) 
    			{
    				ThreadPool.QueueUserWorkItem(new WaitCallback(AccessClassResource),AStudent);
    			}
    
    			Done.WaitOne();
    			Console.WriteLine("All operations have completed. Press enter to exit");
    			Console.ReadLine();
    		}
    	}
    }
  6. Build the project, and then run the application.

REFERENCES

For more information, see the   following Microsoft  Developer Network (MSDN) Web sites:
Thread   Pooling
http://msdn2.microsoft.com/en-us/library/0ka9477y(vs.71).aspx
ReaderWriterLock
http://msdn2.microsoft.com/en-us/library/bz6sth95(vs.71).aspx
ReaderWriterLock   Class
http://msdn2.microsoft.com/en-us/library/system.threading.readerwriterlock(vs.71).aspx

Properties

Article ID: 816161 - Last Review: July 14, 2008 - Revision: 3.1
APPLIES TO
  • Microsoft Visual C# 2008 Express Edition
  • Microsoft Visual C# 2005 Express Edition
  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
Keywords:              
kbthreadsync kbthread kbhowtomaster KB816161

 

JetBrains全家桶生产就绪指南:平台架构、配置避坑与调试实战 JetBrains IDE并非普通编辑器,而是基于IntelliJ Platform构建的四层可插拔开发环境——涵盖Platform Core内核、语言插件、第三方扩展及用户状态配置。其性能瓶颈常源于索引引擎、VFS虚拟文件系统或Xdebug协议兼容性等底层机制,而非表面安装问题。技术价值体现在语义级代码导航、跨框架智能感知与AI辅助编码闭环;典型应用场景包括Spring Boot微服务调试、Webman+Swoole协程断点追踪、.NET项目资源编译集成及团队标准化配置治理。本文聚焦真实工程现场验证的架构 阅读详情

相关推荐

C++ Builder 6 源代码深度解析:从经典VCL框架到现代工程实践

在桌面应用开发领域,快速应用开发(RAD)框架通过可视化组件和事件驱动编程,极大提升了软件构建效率。其核心原理在于将界面设计与业务逻辑分离,通过封装底层系统API(如Windows消息机制和图形设备接口)为可重用的控件库。这种范式不仅加速了原型开发,更在企业级应用、工控系统和数据库前端等场景中证明了其工程价值。以经典的VCL框架为例,它代表了RAD理念在C++环境下的高峰实践。本文聚焦于对C++ Builder 6(BCB6)这一特定历史版本所附带的示例源代码进行体系化研究,旨在挖掘其中关于**数据库访问层

weixin_34163553的博客 331

python携程酒店评论_python爬携程酒店评论,携程酒店评论爬虫

# -*- coding: utf-8 -*-import scrapyimport PyV8import csvimport reimport mathimport timeimport redisimport requestsimport hashlibimport randomuas=["Mozilla/5.0 (Linux; U; Android 5.0.2; zh-CN; Letv X5...

weixin_39934257的博客 2万+

利用MATLAB 4f光学系统,在Python中进行弗劳恩霍夫衍射和傅里叶面滤波——用镜头模拟光学图像处理。.zip

1.版本:matlab2014a/2019b/2024b 2.附赠案例数据可直接运行。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

linux activemq启动失败原因查找

1、状态已经是启动成功 2、在浏览器中输入http://ip:8161/admin确实无法访问 3、查看activeMQ状态,其状态为没有运行 4、查看日志activemq console 最后发现是内存不足,这个问题困扰了挺久,最后还是要多查看日志 ...

才子佳人的博客 1445

利用MATLAB和Excel对逆流双管热交换器的热性能进行分析。.zip

1.版本:matlab2014a/2019b/2024b 2.附赠案例数据可直接运行。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

利用MATLAB对5G NR波束成形技术的性能分析.zip

1.版本:matlab2014a/2019b/2024b 2.附赠案例数据可直接运行。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

32位Linux与64位Linux系统中指针 小小差别

<br />sizeof 笔误<br />....<br />log_error ("#######Test Only - 02: login=%s, operator=%s", login_name, operator_name);<br />....<br />strncpy (operator_name,<br />              login_name,<br />              sizeof (operator_name - 1));<br />....<br />log_e

www861168com的专栏 2491

上市公司赫芬达尔指数、企业勒纳指数(1999-2025年)

上市公司赫芬达尔指数(HHI)和勒纳指数(LI)是衡量市场结构和市场势力(垄断力量)的两个重要指标 赫芬达尔指数(HHI)可衡量一个公司在市场中的相对份额或集中度,通过计算公司在市场中份额的平方和得出。数值越小,说明市场份额分布越分散,竞争程度越高;数值越大,说明市场集中度越高,少数企业占据较大份额,垄断程度越高 勒纳指数(LI)用于衡量企业的市场势力,即企业偏离完全竞争价格、制定高于边际成本的价格的能力,数值越接近1,表示企业市场势力越强,垄断程度越高 本文借鉴刘贯春等(2021)、孙茹峰和李楠博(2024)的思路和方法,分别测算上市公司赫芬达尔指数、勒纳指数: 赫芬达尔指数 = (公司营业收入/同行业同年营业收入合计)的平方和 企业勒纳指数 =(营业收入-营业成本-销售费用-管理费用)/营业收入 一、数据介绍 数据名称:上市公司赫芬达尔指数、企业勒纳指数 数据范围:上市公司 时间范围:1999-2025年 样本数量:85810条 数据来源:上市公司年报 更新时间:2026年11月 数据说明:内含原始数据、测算结果 二、数据指标 股票代码 股票简称 年份 省份 城市 区县 省份代码 城市代码 区县代码 行业代码 行业名称 赫芬达尔指数 勒纳指数 营业收入 营业成本 销售费用 管理费用 三、参考文献 [1]刘贯春,叶永卫,张军.社会保险缴费、企业流动性约束与稳就业——基于《社会保险法》实施的准自然实验[J].中国工业经济,2021,(05):152-169. [2]孙茹峰,李楠博.金融化对企业绿色转型意向的影响研究[J].管理学报,2024,21(11):1612-1620+1677. [3]张倩肖,段义学.数字赋能、产业链整合与全要素生产率[J].经济管理,2023,45(04):5-21. [4]伍兆祥,代吉林,

1128UI自动化测试经验分享-显式等待(二)expected_conditions模块、visibility_of_element_located(locator)

显式等待:expected_conditions模块、visibility_of_element_located(locator)

谢智超的博客 1万+

海康威视后台摄像头视频管理系统

海康威视后台摄像头视频管理系统,vue+py框架

工业互联网工控安全与工业质检AI大模型建设方案.pptx

工业互联网工控安全与工业质检AI大模型建设方案.pptx

不平衡电网下自抗扰顺序模型预测PWM整流器控制仿真模型(Simulink仿真实现)

内容概要:本文围绕面向城市空中交通的多无人机路径规划问题展开研究,提出了一套融合全局规划、动态避障与局部协同调整的综合路径规划方法。研究内容涵盖基于改进RRT算法与图论的全局路径规划、基于动态风险场和动态窗口法(DWA)的模型预测控制实现动态避障,以及基于分布式协同控制的多无人机局部路径协同策略。通过Matlab平台构建仿真环境,在多种典型城市交通场景下对所提方法进行了系统性验证,结果表明该方法在路径安全性、编队稳定性与任务效率方面表现优异。文章还深入探讨了算法的创新点与未来研究方向,为复杂城市环境下多无人机系统的自主协同提供了理论支撑与技术路径。; 适合人群:具备自动化、控制理论、计算机科学或相关领域基础知识,从事无人机系统、智能交通、路径规划、多智能体协同控制等方向研究的研究生、科研人员及工程技术人员。; 使用场景及目标:①为城市空中交通系统中的多无人机安全、高效飞行提供可靠的路径规划解决方案;②支持在复杂、动态的城市场景中开展无人机自主导航、编队飞行与协同控制的技术研究与仿真验证。; 阅读建议:建议结合提供的Matlab代码进行实践操作,重点关注算法的具体实现细节、参数配置对性能的影响以及不同仿真场景下的实验设计,以深入理解各模块的集成逻辑与实际应用效果。

通信行业CentOS 7内核网络栈优化:高并发连接下UDP/TCP性能调优与系统资源管理

内容概要:本文聚焦于CentOS 7系统在通信行业高并发场景下的性能调优实践,重点围绕内核网络栈优化展开,涵盖UDP/TCP缓冲区调整、文件句柄与连接跟踪表扩容、TIME_WAIT状态复用、软中断分布优化及tuned工具的自动化调优。通过具体配置参数和实际案例(如VoIP软交换系统)深入解析各项调优措施的设计原理与实施效果,有效解决高CPS下丢包、连接失败等问题,并展望了向云化、eBPF等动态智能调优方向的发展趋势。; 适合人群:从事通信系统运维、网络开发或Linux系统性能优化的技术人员,具备一定操作系统和网络基础知识,工作经验1年以上的中初级工程师。; 使用场景及目标:①应用于软交换、媒体网关、信令网关等高并发通信设备的系统调优;②解决UDP丢包、conntrack表满、TCP连接队列溢出等典型性能瓶颈;③提升系统在小包高频、低时延要求场景下的稳定性和吞吐能力。; 阅读建议:建议结合实际生产环境或测试平台同步验证文中配置,重点关注参数背后的物理意义(如BDP、softirq、conntrack机制),并配合ss、conntrack、dmesg等命令进行调优前后对比分析,确保安全可控地实施变更。

【选址和定容】模拟退火改进多目标粒子群算法在分布式电源选址和定容中的应用【IEEE69节点】(Matlab代码实现)

内容概要:本文研究了模拟退火改进多目标粒子群算法在分布式电源选址和定容中的应用,以IEEE69节点配电系统为算例进行仿真分析。通过融合模拟退火算法的强全局搜索能力与粒子群算法的高效局部收敛特性,构建了一种改进的多目标优化算法,用于解决分布式电源在配电网中的最优位置选择与容量配置问题。研究旨在实现多重优化目标,包括最小化网络有功损耗、提升节点电压质量、增强系统运行的经济性与稳定性。文中详细阐述了多目标优化模型的数学构建、算法的改进机制与实现流程,并基于Matlab平台完成了算法编程与仿真验证,结果表明所提方法在求解质量和收敛性能上均优于传统算法。; 适合人群:具备电力系统分析、优化理论基础及Matlab编程能力,从事配电网规划、分布式能源系统优化、智能优化算法应用等相关领域的科研人员、工程师以及高校研究生。; 使用场景及目标:①解决高比例分布式电源接入背景下配电网的科学规划问题;②为新型电力系统中源网协调设计提供有效的优化工具;③为相关领域的科研工作提供可复现、可拓展的算法模型与仿真代码实例,支持进一步的算法对比与功能升级。; 阅读建议:建议读者结合提供的Matlab代码与IEEE69节点标准数据,动手复现实验结果,深入理解算法的参数设置、迭代过程与多目标折衷分析方法,并可根据实际研究需求修改目标函数或引入新的约束条件以适应不同的应用场景。

从Elasticsearch的jvm.options读懂JVM参数的生效核验、内存分账与诊断兜底代码包

拿到一台机器和一个 Java 服务,怎样确认 JVM 实际吃进去了哪些参数,怎样给堆和堆外分配内存,怎样把 GC 日志、堆转储、异常栈这些“事后取证”的参数配齐,以及怎样在 JDK 8 与 JDK 9+ 之间安全迁移。 讲解的抓手是 Elasticsearch(下文简称 ES)的 jvm.options。这份文件经过 ES 团队多年打磨,又被无数生产集群验证过,几乎每一行都对应一个踩过的坑,是学习 JVM 参数最好的“样板间”。

2024 《计算机网络》实验教学指导书.doc

2024 《计算机网络》实验教学指导书.doc

无刷直流电机BLDC无感+滑模观测器+转速电流双闭环PI控制(总共三个仿真模型)(Simulink仿真实现)

内容概要:本文档系统性地提供了无刷直流电机(BLDC)的高级控制策略仿真资源,聚焦于无位置传感器控制技术,重点实现了基于滑模观测器(SMO)的转子位置估算方法,并结合转速与电流双闭环PI控制结构,构建了完整的Simulink仿真模型体系。资源包含三个核心仿真模型:无感控制下的滑模观测器设计、双闭环PI控制器的参数整定与动态调节,以及系统整体的运行性能仿真分析。文档深入剖析了滑模观测器在反电动势提取与相位补偿中的关键技术,展示了其在不同工况下对电机启动、调速及负载扰动响应的鲁棒性表现,旨在帮助研究人员掌握BLDC在无传感器条件下的高精度控制实现路径,并为进一步引入模糊PID等先进控制策略提供对比基准与技术支撑。; 适合人群:具备电机控制理论基础、自动控制原理知识及Simulink建模经验,从事电气工程、自动化、电力电子或新能源驱动系统研究的科研人员、工程技术人员及高校研究生。; 使用场景及目标:①深入理解无刷直流电机无位置传感器控制的基本原理与实现流程;②掌握滑模观测器在转子位置与速度估算中的设计方法及其抗干扰特性;③学习并优化转速电流双闭环PI控制结构,提升系统动态响应性能与运行稳定性。; 阅读建议:建议结合Simulink模型进行同步仿真操作,重点关注滑模观测器的抖振抑制效果、系统启动过程的稳定性以及PI参数调节对动态性能的影响,同时可参照文档中提及的模糊PID等对比方案,拓展对先进控制算法的研究与实践应用。

Silvaco二极管、三极管、CMOS的制备

Silvaco二极管和三极管的制备

yytu231的博客 5749
上一篇: 数据结构(C#):队列
下一篇: 难道调用ThreadPool.QueueUserWorkItem()的时候,真是必须调用Thread.Sleep(N)吗?
ArvinStudy
博客等级 码龄15年 83粉丝 193原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值