VB.NET并行与分布式编程(3)-线程局部存储TLS[1]

一、TLS种类

1)动态TLS

2)静态TLS

静态TLS的速度比动态TLS快,在编译期就决定,需要定义一个静态域来表示TLS数据,编译器有足够的信息来在编译期间内发射代码,动态TLS需要通过一个或多个函数调用来获得地址。

二、静态TLS

我们可以在线程函数中使用static声明一个静态的变量,这个变量会被所有使用这个函数的线程共享。比如,我们写一个简单的计算:

 200-1-2-....-20

其中减法部分有3个线程来完成,则意味着3个线程要共享一个临时的计算结果

 

 

Imports System
Imports System.Threading


Module Module1

    Sub Main()

        Dim mythread1 As Thread
        Dim mythread2 As Thread
        Dim mythread3 As Thread
        '创建线程对象
      mythread1 = New Thread(AddressOf mythreadrun)
        mythread2 = New Thread(AddressOf mythreadrun)
        mythread3 = New Thread(AddressOf mythreadrun)
        Console.WriteLine(Now.ToLongTimeString & "线程对象创建完毕,开始执行线程")

        '执行线程
     mythread1.Start("线程1")
        mythread2.Start("线程2")
        mythread3.Start("线程3")
        '等待线程完成
     mythread1.Join()
        mythread2.Join()
        mythread3.Join()
        '线程执行完毕
        Console.WriteLine(Now.ToLongTimeString & "线程执行完毕!")
    End Sub
    Public Sub mythreadrun(ByVal data As Object)
        Dim mynum As Integer
        Static jg As Integer = 200
        Dim temp As Integer
        Try
            For mynum = 1 To 20
                temp = jg
                jg -= mynum
                Console.WriteLine(data & ":" & Now.ToLongTimeString & "=>" & temp & "-" & mynum & ",计算结果为:" & jg)
                Thread.Sleep(1)
            Next
        Catch
            Console.WriteLine(data & ":" & Now.ToLongTimeString & "线程异常终止!")
            '终止线程
            Thread.CurrentThread.Abort()
        End Try
    End Sub
End Module

          Dim mynum As Integer
        Static jg As Integer = 200
        Dim temp As Integer
        Try
            For mynum = 1 To 20
                temp = jg
                jg -= mynum
                Console.WriteLine(data & ":" & Now.ToLongTimeString & "=>" & temp & "-" & mynum & ",计算结果为:" & jg)
                Thread.Sleep(1)
            Next

 

jg就是一个静态域,被多个线程共享

运行结果如下



 

 

我们使用静态TLS功能,让jg成为一个线程本地变量,对每个线程而言,都是

在操作这个变量的副本

 

在某些多线程方案中,可能要为每个线程提供它自己的私有数据。 此类数据称为“线程本地数据”。 在 .NET Framework 3.5 和更低版本中,可以将 ThreadStatic 特性应用于静态变量以使其成为线程本地变量。 但是,使用 ThreadStatic 特性会导致细小的错误。 例如,即使基本的初始化语句也将导致该变量只在访问它的第一个线程上进行初始化,如以下示例中所示: 

<ThreadStaticAttribute> _
Shared counter As Integer

比如:

Imports System
Imports System.Threading

Class Test

    <MTAThread> _
    Shared Sub Main()

        For i As Integer = 1 To 3
            Dim newThread As New Thread(AddressOf ThreadData.ThreadStaticDemo)
            newThread.Start()
        Next i

    End Sub

End Class

Class ThreadData

    <ThreadStaticAttribute> _
    Shared threadSpecificData As Integer

    Shared Sub ThreadStaticDemo()

        ' Store the managed thread id for each thread in the static
        ' variable.
        threadSpecificData = Thread.CurrentThread.ManagedThreadId

        ' Allow other threads time to execute the same code, to show
        ' that the static data is unique to each thread.
        Thread.Sleep( 1000 )

        ' Display the static data.
        Console.WriteLine( "Data for managed thread {0}: {1}", _
            Thread.CurrentThread.ManagedThreadId, threadSpecificData )

    End Sub

End Class

' This code example produces output similar to the following:
'
'Data for managed thread 4: 4
'Data for managed thread 5: 5
'Data for managed thread 3: 3

 

在所有其他线程上,该变量将通过使用默认值(零)来进行初始化。

 


我们在.net 4.0也就是说vb.net 2010中,使用替代方案:

,可以使用 System.Threading.ThreadLocal(Of T) 类型创建基于实例的线程本地变量,此变量可通过您提供的 Action(Of T) 委托在所有线程上进行初始化。

Imports System
Imports System.Threading


Module Module1

    Sub Main()

        Dim mythread1 As Thread
        Dim mythread2 As Thread
        Dim mythread3 As Thread
        '创建线程对象
        mythread1 = New Thread(AddressOf mythreadrun)
        mythread2 = New Thread(AddressOf mythreadrun)
        mythread3 = New Thread(AddressOf mythreadrun)
        Console.WriteLine(Now.ToLongTimeString & "线程对象创建完毕,开始执行线程")

        '执行线程
        mythread1.Start("线程1")
        mythread2.Start("线程2")
        mythread3.Start("线程3")
        '等待线程完成
        mythread1.Join()
        mythread2.Join()
        mythread3.Join()
        '线程执行完毕
        Console.WriteLine(Now.ToLongTimeString & "线程执行完毕!")
    End Sub
    Public Sub mythreadrun(ByVal data As Object)
        Dim mynum As Integer
        Dim jg As ThreadLocal(Of Integer) = New ThreadLocal(Of Integer)(Function() 50)
        Try
            For mynum = 1 To 5
                jg.Value -= mynum
                Console.WriteLine(data & "  " & Now.ToLongTimeString & "=>" & (jg.Value + mynum) & "-" & mynum & ",计算结果为:" & jg.Value)
                Thread.Sleep(2)
            Next
        Catch
            Console.WriteLine(data & "  " & Now.ToLongTimeString & "线程异常终止!")
            '终止线程
            Thread.CurrentThread.Abort()
        End Try
    End Sub
End Module

 
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值