.Net多线程Threading相关详解

一、线程不安全例子

计数

cs 复制代码
const int total = 100_000;

int count = 0;

var thread1 = new Thread(Increment);
var thread2 = new Thread(Increment);

thread1.Start();
thread2.Start();

thread1.Join();
thread2.Join();

Console.WriteLine($"Count: {count}");

void Increment()
{
    for (int i = 0; i < total; i++)
        count++;
}

操作队列

cs 复制代码
var queue = new Queue<int>();

var producer = new Thread(Producer);
var consumer1 = new Thread(Consumer);
var consumer2 = new Thread(Consumer);

producer.Start();
consumer1.Start();
consumer2.Start();

producer.Join();
Thread.Sleep(100); // Wait for consumers to finish

consumer1.Interrupt();
consumer2.Interrupt();
consumer1.Join();
consumer2.Join();

void Producer()
{
    for (int i = 0; i < 20; i++)
    {
        Thread.Sleep(20);
        queue.Enqueue(i);
    }
}

void Consumer()
{
    try
    {
        while (true)
        {
            if (queue.TryDequeue(out var res))
                Console.WriteLine(res);
            Thread.Sleep(1);
        }
    }
    catch (ThreadInterruptedException)
    {
        Console.WriteLine("Thread interrupted.");
    }
}

二、Parallel与PLINQ

cs 复制代码
var inputs = Enumerable.Range(1,20).ToArray();

int HeavyJob(int input)
{
    Thread.Sleep(300);
    return input;
}

// Sequential
var forOutputs = new int[inputs.Length];
for (int i = 0; i < inputs.Length; i++)
{
    forOutputs[i] = HeavyJob(inputs[i]);
}

// Parallel
var parallelOutputs = new int[inputs.Length];
Parallel.For(0, inputs.Length, i =>
{
    parallelOutputs[i] = HeavyJob(inputs[i]);
});

// PLINQ
var plinqOutputs = inputs.AsParallel().Select(HeavyJob).ToArray();

三、PLINQ 与信号量

cs 复制代码
using System.Diagnostics;

var inputs = Enumerable.Range(1,20).ToArray();
var semaphore = new Semaphore(3, 3);

int HeavyJob(int input)
{
    semaphore.WaitOne();
    Thread.Sleep(300);
    semaphore.Release();
    return input;
}

var sw = Stopwatch.StartNew();
var plinqOutputs = inputs.AsParallel().Select(HeavyJob).ToArray();
sw.Stop();
Console.WriteLine($"Elapsed time: {sw.ElapsedMilliseconds}ms");

四、线程终止

cs 复制代码
//线程终止
var thread = new Thread(() =>
{
    try
    {
        for (int i = 0; i < 10; i++)
        {
            Thread.Sleep(1000);
            Console.WriteLine("Sub thread: " + i);
        }
    }
    catch (ThreadInterruptedException)
    {
        Console.WriteLine("Thread interrupted");
    }
});

thread.Start();
Thread.Sleep(3500);
thread.Interrupt();
thread.Join();
Console.WriteLine("Done");
相关推荐
九河云1 小时前
AWS账号注册费用详解:新用户是否需要付费?
服务器·云计算·aws
Lary_Rock1 小时前
RK3576 LINUX RKNN SDK 测试
linux·运维·服务器
幺零九零零2 小时前
【计算机网络】TCP协议面试常考(一)
服务器·tcp/ip·计算机网络
XiaoLeisj2 小时前
【JavaEE初阶 — 多线程】单例模式 & 指令重排序问题
java·开发语言·java-ee
paopaokaka_luck2 小时前
【360】基于springboot的志愿服务管理系统
java·spring boot·后端·spring·毕业设计
dayouziei2 小时前
java的类加载机制的学习
java·学习
云飞云共享云桌面3 小时前
8位机械工程师如何共享一台图形工作站算力?
linux·服务器·网络
励志成为嵌入式工程师3 小时前
c语言简单编程练习9
c语言·开发语言·算法·vim
捕鲸叉3 小时前
创建线程时传递参数给线程
开发语言·c++·算法
A charmer3 小时前
【C++】vector 类深度解析:探索动态数组的奥秘
开发语言·c++·算法