多线程共享功能和子 [英] multiple threads sharing functions and sub

查看:69
本文介绍了多线程共享功能和子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我在几个线程将要使用的模块中具有三个功能.除主doWork子控件外,所有函数均访问局部变量.

Hello,

i have three functions in a module that several threads would be using. all of the functions access local variable except the main doWork sub.

Sub DoWork(byval i as integer)

synclock (ListTasks)
dim strItem  as string =ListTasks(CInt(i)).ToString
end SyncLock

dim strHtml as string = GetHtml(strItem )
dim strParsed as string = ParseHtml(strHtml)
dim strResult as string = Report(strParsed )
End sub

Function GetHtml(byval url as string) as string
''code to get website
ens sub

Function ParseHtml(Byval html as string) as string
''code to parse HtmlString
end function

Function Report(Byval html as string) as string
''do the work
end function





Is this a thread safe code?

推荐答案

已阅读此CP文章 ^ ]
Have a read of this CP article Introduction to making multithreaded VB.NET Apps[^]


让我解释一下.

函数无关紧要,线程无关紧要.我的意思是,可以在不同的线程中调用相同的函数.该函数的作用在一种情况下是线程安全的,而在另一种情况下则不是线程安全的.

因此,伪造函数,焦点和线程以及访问哪些资源.如果有多个线程访问同一资源,则应使用某种锁定机制将访问代码锁定.在这种情况下,代码本身可以是从不同线程调用的相同线程,也可以是不同线程;没关系;这段代码访问的内容很重要.

锁定不是唯一的事情.例如,可以通过将委托(代码)或数据放入队列中来序列化呼叫.例如,请参阅此处的提示/技巧文章: Simple Blocking Queue for线程通信和线程间调用 [ ^ ].

—SA
Let me explain it.

Functions don''t matter, the threads do. I mean, the same function can be called in different threads. What the function does is thread-safe in one case and not thread-safe in another.

Therefore, forger about functions and focus and threads and what resources are accessed. If more then one thread access the same resource, the access code should be locked out using some lock mechanism. In this case, the code itself can be the same called from different thread, of different; it does not matter; it''s only important what is accessed by this code.

Locking is not the only thing. Calls can be serialized for example, by putting the delegates (code) or data in a queue. For example, see my short Tips/Trick article here: Simple Blocking Queue for Thread Communication and Inter-thread Invocation[^].

—SA


否.


这篇关于多线程共享功能和子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆