Threading Question(s)

M

Mythran

Sample Code (top of head):

Private mThread As Thread
Private mCounter As Long

Sub StartThread()
mThread = New Thread(AddressOf StartLoop)
mThread.Start()
End Sub

Sub StopThread()
mThread.Abort()
mThread = Nothing
MsgBox(mCounter)
End Sub

Sub StartLoop()
mCounter = 0

While True
mCounter += 1
End While
End Sub

Sub btnStartStop_Click(sender As Object, e As EventArgs) Handles
btnStart.Click, btnStop.Click
If mThread Is Nothing
StartThread()
Else
StopThread()
End If
End Sub


Now...questions:

1.) Doesn't look thread safe to me. Is It? Referring to the accessing of
the mCounter variable.
2.) How can I make it thread safe and still use the variable in both
threads? (IE: Locking var somehow???)
3.) How can I transfer data between threads? Whether it is an intrinsic
data type or not...
4.) How can I automatically detect the thread is being aborted? Basically
like an event...

Just some curiosity about threading that I have while running some thread
tests this morn :)

Mythran
 
M

Mattias Sjögren

1.) Doesn't look thread safe to me. Is It? Referring to the accessing of
the mCounter variable.

It depends what you mean by safe. Since you only have one thread
writing the value nothing terribly wrong will happen. But since you
don't use any form of synchronization I wouldn't call it thread safe.

2.) How can I make it thread safe and still use the variable in both
threads? (IE: Locking var somehow???)

You usually use the SyncLock statement or some synchronization class
from the System.Threading namespace, depending on how you want to
access the data. But in this example (somewhat contrived it seems)
where you're only reading the value after the writing thread has been
terminated, it may not be needed.

3.) How can I transfer data between threads? Whether it is an intrinsic
data type or not...

Data is usually shared by and available to all threads - that's why
you need synchronization to begin with. Only stack allocated data and
fields marked with the ThreadLocal attribute are specific to a certain
thread.

4.) How can I automatically detect the thread is being aborted? Basically
like an event...

A ThreadAbortException is thrown. But there are better ways to
gracefully shut down a background thread than to Abort it.



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top