.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");
相关推荐
gywl7 分钟前
openEuler VM虚拟机操作(期末考试)
linux·服务器·网络·windows·http·centos
轻口味11 分钟前
命名空间与模块化概述
开发语言·前端·javascript
苹果醋31 小时前
React源码02 - 基础知识 React API 一览
java·运维·spring boot·mysql·nginx
晓纪同学1 小时前
QT-简单视觉框架代码
开发语言·qt
威桑1 小时前
Qt SizePolicy详解:minimum 与 minimumExpanding 的区别
开发语言·qt·扩张策略
Hello.Reader1 小时前
深入解析 Apache APISIX
java·apache
飞飞-躺着更舒服1 小时前
【QT】实现电子飞行显示器(简易版)
开发语言·qt
了一li1 小时前
Qt中的QProcess与Boost.Interprocess:实现多进程编程
服务器·数据库·qt
明月看潮生1 小时前
青少年编程与数学 02-004 Go语言Web编程 16课题、并发编程
开发语言·青少年编程·并发编程·编程与数学·goweb
明月看潮生1 小时前
青少年编程与数学 02-004 Go语言Web编程 17课题、静态文件
开发语言·青少年编程·编程与数学·goweb