惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
Netflix TechBlog - Medium
V
Vulnerabilities – Threatpost
Google Online Security Blog
Google Online Security Blog
Hugging Face - Blog
Hugging Face - Blog
L
LINUX DO - 热门话题
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
D
Docker
C
Cyber Attacks, Cyber Crime and Cyber Security
MyScale Blog
MyScale Blog
P
Palo Alto Networks Blog
T
Tenable Blog
P
Privacy International News Feed
Google DeepMind News
Google DeepMind News
小众软件
小众软件
Cisco Talos Blog
Cisco Talos Blog
aimingoo的专栏
aimingoo的专栏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
Arctic Wolf
C
Cybersecurity and Infrastructure Security Agency CISA
C
Cisco Blogs
T
Threat Research - Cisco Blogs
NISL@THU
NISL@THU
The Hacker News
The Hacker News
Project Zero
Project Zero
AWS News Blog
AWS News Blog
Simon Willison's Weblog
Simon Willison's Weblog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Threatpost
V
Visual Studio Blog
The GitHub Blog
The GitHub Blog
The Cloudflare Blog
Last Week in AI
Last Week in AI
Jina AI
Jina AI
Cyberwarzone
Cyberwarzone
The Register - Security
The Register - Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
Vercel News
Vercel News
D
Darknet – Hacking Tools, Hacker News & Cyber Security
MongoDB | Blog
MongoDB | Blog
U
Unit 42
Scott Helme
Scott Helme
A
About on SuperTechFans
WordPress大学
WordPress大学
F
Fortinet All Blogs
大猫的无限游戏
大猫的无限游戏
G
GRAHAM CLULEY
Latest news
Latest news
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
Schneier on Security

博客园 - 言午

Nopcommerce 二次开发2 Admin Nopcommerce 二次开发1 基础 Nopcommerce 二次开发2 WEB Nopcommerce 二次开发0 sqlce中不支持sp_rename修改表名 C#读取Excel遇到无法读取的解决方法 狼奔代码生成器 银行账户类 累 interface 抽象类 抽象方法 Message 类的继承 多态(虚方法) 事件event 委托 代理 索引! 第五周作业 第四周作业 考试! 线程安全 二
线程安全 一
言午 · 2011-11-15 · via 博客园 - 言午

using System;
using System.Threading;
using System.Runtime.Remoting.Contexts;
using System.Runtime.CompilerServices;

// Note that the instance variable count is shared between the two methods Read
// and Increment. Threads concurrently executing one or both of these methods can
// interfere with each other unless action is taken to synchronize access

class CounterUnsafe
{
    int count = 0;

    public void Increment() 
    {
        // following code is not thread-safe and has a race condition
        Console.WriteLine(
            "Start Resource writing count: {0}", count);
        // the following four lines simulate count++ with a very large
        
// window of time between count being read and being incremented.
        
// This large window ensures that the race condition will create
        
// errors often when the code is accessed concurrently by multiple threads.
        int tempCount = count;
        Thread.Sleep(50);
        tempCount++;
        count = tempCount;
        Console.WriteLine(
            "Stop  Resource writing count: {0}",  count);
    }
}

// Context-bound type with the Synchronization context attribute.
[Synchronization()]
class CounterSynchronizedContext : ContextBoundObject
{
    static int staticCount = 0;
    int instanceCount = 0;

    public void IncrementInstance() 
    {
        Console.WriteLine(
            "Start Object:{0} Thread:{1}  Resource writing count, instance:{2}"
            this.GetHashCode(), Thread.CurrentThread.GetHashCode(),
            instanceCount);
        int tempStaticCount = staticCount;
        int tempInstanceCount = instanceCount;
        Thread.Sleep(50);
        tempInstanceCount++;
        instanceCount = tempInstanceCount;
        Console.WriteLine(
            "Stop Object:{0} Thread:{1}  Resource writing count, instance:{2}"
            this.GetHashCode(), Thread.CurrentThread.GetHashCode(),
            instanceCount);
    }    
    
     public static void IncrementStatic() 
        {
            Console.WriteLine(
                "Start Thread:{0}  Resource writing count, static:{1}"
                Thread.CurrentThread.GetHashCode(),
                staticCount);
            int tempStaticCount = staticCount;
            Thread.Sleep(50);
            tempStaticCount++;
            staticCount = tempStaticCount;
            Console.WriteLine(
                "Stop Thread:{0}  Resource writing count, static:{1}"
                Thread.CurrentThread.GetHashCode(),
                staticCount);
        }
}
class CounterSynchronizedCodeRegion
{
    static int staticCount = 0;
    int instanceCount = 0;

    [MethodImplAttribute(MethodImplOptions.Synchronized)]
    public void IncrementInstance() 
    {
        Console.WriteLine(
            "Start Object:{0} Thread:{1}  Resource writing count, instance:{2}"
            this.GetHashCode(), Thread.CurrentThread.GetHashCode(),
            instanceCount);
        int tempInstanceCount = instanceCount;
        Thread.Sleep(50);
        tempInstanceCount++;
        instanceCount = tempInstanceCount;
        Console.WriteLine(
            "Stop Object:{0} Thread:{1}  Resource writing count, instance:{2}"
            this.GetHashCode(), Thread.CurrentThread.GetHashCode(),
            instanceCount);
    }

    [MethodImplAttribute(MethodImplOptions.Synchronized)]
     public static void IncrementStatic() 
    {
        Console.WriteLine(
        "Start Thread:{0}  Resource writing count, static:{1}"
            Thread.CurrentThread.GetHashCode(),
            staticCount);
        int tempStaticCount = staticCount;
        Thread.Sleep(50);
        tempStaticCount++;
        staticCount = tempStaticCount;
        Console.WriteLine(
            "Stop Thread:{0}  Resource writing count, static:{1}"
            Thread.CurrentThread.GetHashCode(),
            staticCount);
    }
}

class App 
{
    public static void Main() 
    {
        Thread t1, t2, t3;
        Console.WriteLine("\n\nStarting Unsafe Test");
        CounterUnsafe counterUnsafe = new CounterUnsafe();
        t1 = new 
            Thread(    new 
                ThreadStart(counterUnsafe.Increment)); 
        t1.Start();
        t2 = new 
            Thread(    new 
                ThreadStart(counterUnsafe.Increment)); 
        t2.Start();
        t3 = new 
            Thread(    new 
                ThreadStart(counterUnsafe.Increment)); 
        t3.Start();
        // wait for all threads to indicate that they are done.
        t1.Join();t2.Join();t3.Join();
        Console.WriteLine("All Unsafe threads have completed.");
        
        // Synchronized context doesn't prevent static methods from concurrently executing
        Console.WriteLine("\n\nStarting Static Method Synchronized Context Test");
        t1 = new 
            Thread(    new 
            ThreadStart(CounterSynchronizedContext.IncrementStatic)); 
        t1.Start();
        t2 = new 
            Thread(    new 
            ThreadStart(CounterSynchronizedContext.IncrementStatic)); 
        t2.Start();
        t3 = new 
            Thread(    new 
            ThreadStart(CounterSynchronizedContext.IncrementStatic)); 
        t3.Start();

        // wait for all threads to indicate that they are done.
        t1.Join();t2.Join();t3.Join();
        Console.WriteLine("All Static Method Synchronized Context threads have completed.");
        
        // Synchronized context does prevent instance methods from concurrently executing
        Console.WriteLine("\n\nStarting Instance Method Synchronized Context Test");
        CounterSynchronizedContext counterSynchronizedContext = new CounterSynchronizedContext();
        t1 = new 
            Thread(    new 
            ThreadStart(counterSynchronizedContext.IncrementInstance)); 
        t1.Start();
        t2 = new 
            Thread(    new 
            ThreadStart(counterSynchronizedContext.IncrementInstance)); 
        t2.Start();
        t3 = new 
            Thread(    new 
            ThreadStart(counterSynchronizedContext.IncrementInstance)); 
        t3.Start();

        // wait for all threads to indicate that they are done.
        t1.Join();t2.Join();t3.Join();
        Console.WriteLine("All Instance Method Synchronized Context threads have completed.");
        
        Console.WriteLine("\n\nStarting Static Method Synchronized Code Region Test");
        t1 = new 
            Thread(    new 
            ThreadStart(CounterSynchronizedCodeRegion.IncrementStatic)); 
        t1.Start();
        t2 = new 
            Thread(    new 
            ThreadStart(CounterSynchronizedCodeRegion.IncrementStatic)); 
        t2.Start();
        t3 = new 
            Thread(    new 
            ThreadStart(CounterSynchronizedCodeRegion.IncrementStatic)); 
        t3.Start();
        // wait for all threads to indicate that they are done.
        t1.Join();t2.Join();t3.Join();

        Console.WriteLine("All Static Method Synchronized Code Region threads have completed.");
        
        // Method Synchronization is similar to Monitor and prevents 
        
// concurrent access to both static and instance methods
        Console.WriteLine("\n\nStarting Instance Method Synchronized Code Region Test");
        CounterSynchronizedCodeRegion counterSynchronizedCodeRegion = new CounterSynchronizedCodeRegion();
        t1 = new 
            Thread(    new 
            ThreadStart(counterSynchronizedCodeRegion.IncrementInstance)); 
        t1.Start();
        t2 = new 
            Thread(    new 
            ThreadStart(counterSynchronizedCodeRegion.IncrementInstance)); 
        t2.Start();
        t3 = new 
            Thread(    new 
            ThreadStart(counterSynchronizedCodeRegion.IncrementInstance)); 
        t3.Start();

        // wait for all threads to indicate that they are done.
        t1.Join();t2.Join();t3.Join();
        Console.WriteLine("All Static Method Synchronized Code Region threads have completed.");

    }

}