473,804 Members | 2,124 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Multithread Stop/Restart

Hi all,

I have 3 running threads chencking for something in my application.
Based on that I need to stop some of them safely wait for something
else and restart. Sleep is not good in my case because i don't know how
much to wait. How and from where I can put a thread in pause an restart
it?

Thank you
Juky
Sub main ()
....
t1 = New Threading.Threa d(AddressOf Check1)
t1.Start()
t2 = New Threading.Threa d(AddressOf Check2)
t2.Start()
t3 = New Threading.Threa d(AddressOf Check3)
t3.Start()
end sub

sub Check1()
while true
"IF CHECK=TRUE THEN I HAVET TO SUSPEND THIS THREAD
end while
end Sub

sub Check2()
while true
"IF CHECK=TRUE THEN I HAVET TO SUSPEND THIS THREAD
end while
end Sub

sub Check3()
while true
"IF CHECK=TRUE THEN I HAVET TO SUSPEND THIS THREAD
end while
end Sub

Nov 21 '05 #1
5 2106
Juky,

Are you sure you need those threads.

Remember that the processing time of an applications with multithreading is
longer than withouth that.

When there are a lot of dependencies that can be as well for the throughput
time.

Cor
Nov 21 '05 #2
One way to do it is to have an appropriately scoped boolean variable (check)
and set/reset it as required in your external code. In you thread(s), handle
the condition thus:

Sub Check1()

Do

If Not check Then

' Do whatever needs doing

End If

Loop

End Sub

Whatever processing the thread does will effectively be suspended while
check it set.
Note that if check is set while the thread is actually doing it's processing
then the 'suspension' will not be effective until the next iteration of the
loop, but this should give you the general idea.
"juky" <ju*******@yaho o.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
Hi all,

I have 3 running threads chencking for something in my application.
Based on that I need to stop some of them safely wait for something
else and restart. Sleep is not good in my case because i don't know how
much to wait. How and from where I can put a thread in pause an restart
it?

Thank you
Juky
Sub main ()
....
t1 = New Threading.Threa d(AddressOf Check1)
t1.Start()
t2 = New Threading.Threa d(AddressOf Check2)
t2.Start()
t3 = New Threading.Threa d(AddressOf Check3)
t3.Start()
end sub

sub Check1()
while true
"IF CHECK=TRUE THEN I HAVET TO SUSPEND THIS THREAD
end while
end Sub

sub Check2()
while true
"IF CHECK=TRUE THEN I HAVET TO SUSPEND THIS THREAD
end while
end Sub

sub Check3()
while true
"IF CHECK=TRUE THEN I HAVET TO SUSPEND THIS THREAD
end while
end Sub

Nov 21 '05 #3
"juky" <ju*******@yaho o.com> schrieb:
I have 3 running threads chencking for something in my application.
Based on that I need to stop some of them safely wait for something
else and restart. Sleep is not good in my case because i don't know how
much to wait. How and from where I can put a thread in pause an restart
it?


The sample below will start a thread that waits (blocks the thread) until an
event occurs:

\\\
Imports System.Threadin g

Public Module Program
Private SampleTest As New Test()

Public Sub Main()
Dim t As New Thread(AddressO f SampleTest.Foo)
t.Start()
Console.ReadLin e()
SampleTest.Even tHandler()
End Sub
End Module

Public Class Test
Private EventOccured As New ManualResetEven t(False)

Public Sub Foo()
Debug.WriteLine ("Started!")
EventOccured.Wa itOne(-1, False)
Debug.WriteLine ("Event occured!")
End Sub

Public Sub EventHandler()
EventOccured.Se t()
End Sub
End Class
///

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>

Nov 21 '05 #4
Juky,
As Herfried suggests I would use a ManualResetEven t.

Here is a an example I posted a few weeks ago of a Worker class using a
ManualResetEven t to control suspending & resuming.

Public Class Worker

Public Delegate Sub Work()

Private ReadOnly m_work As Work
Private ReadOnly m_arg As Object
Private ReadOnly m_event As ManualResetEven t
Private ReadOnly m_thread As Thread

<ThreadStatic() > _
Private Shared m_current As Worker

Public Sub New(ByVal work As Work, ByVal arg As Object, ByVal name
As String)
m_work = work
m_arg = arg
m_event = New ManualResetEven t(True)
m_thread = New Thread(AddressO f Start)
m_thread.Name = name
m_thread.IsBack ground = True
m_thread.Start( )
End Sub

Private Sub Start()
m_current = Me
m_work.Invoke()
End Sub

Public Shared ReadOnly Property CurrentWorker() As Worker
Get
Return m_current
End Get
End Property

Public ReadOnly Property Arg() As Object
Get
Return m_arg
End Get
End Property

Public ReadOnly Property Name() As String
Get
Return m_thread.Name
End Get
End Property

Public Sub Suspend()
If Thread.CurrentT hread Is m_thread Then
Throw New InvalidOperatio nException("Sus pend should not be
called from the worker thread!")
End If
m_event.Reset()
End Sub

Public Sub [Resume]()
If Thread.CurrentT hread Is m_thread Then
Throw New InvalidOperatio nException("Res ume should not be
called from the worker thread!")
End If
m_event.Set()
End Sub

Public Sub WaitForTerminat ion()
If Thread.CurrentT hread Is m_thread Then
Throw New InvalidOperatio nException("Wai tForTermination
should not be called from the worker thread!")
End If
m_thread.Join()
End Sub

Public Sub CheckSuspend()
If Not Thread.CurrentT hread Is m_thread Then
Throw New InvalidOperatio nException("Che ckSuspend should
only be called from the worker thread!")
End If
m_event.WaitOne ()
End Sub

End Class

To see how it works try something like:

Private Sub Work()
For index As Integer = 1 To 50
Worker.CurrentW orker.CheckSusp end()
Debug.WriteLine (index, Worker.CurrentW orker.Name)
Dim value As Double = DirectCast(Work er.CurrentWorke r.Arg,
Double)
Thread.Sleep(Ti meSpan.FromSeco nds(value))
Next
End Sub

Public Sub Main()
Dim worker1 As New Worker(AddressO f Work, 0.25, "worker1")
Dim worker2 As New Worker(AddressO f Work, 0.5, "worker2")
Dim worker3 As New Worker(AddressO f Work, 0.75, "worker3")

Debug.WriteLine ("Pausing 5 seconds", "Main")
Thread.Sleep(Ti meSpan.FromSeco nds(5))
worker1.Suspend ()

Debug.WriteLine ("Pausing 5 seconds", "Main")
Thread.Sleep(Ti meSpan.FromSeco nds(5))
worker2.Suspend ()

Debug.WriteLine ("Pausing 5 seconds", "Main")
Thread.Sleep(Ti meSpan.FromSeco nds(5))
worker3.Suspend ()

Debug.WriteLine ("Pausing 1 seconds", "Main")
Thread.Sleep(Ti meSpan.FromSeco nds(1))

worker1.Resume( )
worker2.Resume( )
worker3.Resume( )

Debug.WriteLine ("Waiting for Termination", "Main")
worker1.WaitFor Termination()
worker2.WaitFor Termination()
worker3.WaitFor Termination()

End Sub

The above sample was posted in a thread titled "Technique for Pausing Worker
Thread" in this newsgroup between 21 Jan 2005 & 23 Jan 2005.

Hope this helps
Jay
"juky" <ju*******@yaho o.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
Hi all,

I have 3 running threads chencking for something in my application.
Based on that I need to stop some of them safely wait for something
else and restart. Sleep is not good in my case because i don't know how
much to wait. How and from where I can put a thread in pause an restart
it?

Thank you
Juky
Sub main ()
....
t1 = New Threading.Threa d(AddressOf Check1)
t1.Start()
t2 = New Threading.Threa d(AddressOf Check2)
t2.Start()
t3 = New Threading.Threa d(AddressOf Check3)
t3.Start()
end sub

sub Check1()
while true
"IF CHECK=TRUE THEN I HAVET TO SUSPEND THIS THREAD
end while
end Sub

sub Check2()
while true
"IF CHECK=TRUE THEN I HAVET TO SUSPEND THIS THREAD
end while
end Sub

sub Check3()
while true
"IF CHECK=TRUE THEN I HAVET TO SUSPEND THIS THREAD
end while
end Sub

Nov 21 '05 #5
I missed an addendum to the original thread:

An alternate Worker.Suspend implementation might be:

Public Sub Suspend()
m_event.Reset()
If Thread.CurrentT hread Is m_thread Then
m_event.WaitOne ()
End If
End Sub

Which allows the worker thread to suspend itself.

I would also consider implementing CurrentWorker as:

Public Shared ReadOnly Property CurrentWorker() As Worker
Get
If m_current Is Nothing Then
Throw New InvalidOperatio nException("Cur rentWorker
should only be called from a Worker thread!")
End If
Return m_current
End Get
End Property

To ensure that it is only called from Worker Threads (preventing
NullReferenceEx ceptions in non-worker threads!).

Hope this helps
Jay
"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in message
news:uf******** ******@TK2MSFTN GP15.phx.gbl...
Juky,
As Herfried suggests I would use a ManualResetEven t.

Here is a an example I posted a few weeks ago of a Worker class using a
ManualResetEven t to control suspending & resuming.

Public Class Worker

Public Delegate Sub Work()

Private ReadOnly m_work As Work
Private ReadOnly m_arg As Object
Private ReadOnly m_event As ManualResetEven t
Private ReadOnly m_thread As Thread

<ThreadStatic() > _
Private Shared m_current As Worker

Public Sub New(ByVal work As Work, ByVal arg As Object, ByVal name
As String)
m_work = work
m_arg = arg
m_event = New ManualResetEven t(True)
m_thread = New Thread(AddressO f Start)
m_thread.Name = name
m_thread.IsBack ground = True
m_thread.Start( )
End Sub

Private Sub Start()
m_current = Me
m_work.Invoke()
End Sub

Public Shared ReadOnly Property CurrentWorker() As Worker
Get
Return m_current
End Get
End Property

Public ReadOnly Property Arg() As Object
Get
Return m_arg
End Get
End Property

Public ReadOnly Property Name() As String
Get
Return m_thread.Name
End Get
End Property

Public Sub Suspend()
If Thread.CurrentT hread Is m_thread Then
Throw New InvalidOperatio nException("Sus pend should not be
called from the worker thread!")
End If
m_event.Reset()
End Sub

Public Sub [Resume]()
If Thread.CurrentT hread Is m_thread Then
Throw New InvalidOperatio nException("Res ume should not be
called from the worker thread!")
End If
m_event.Set()
End Sub

Public Sub WaitForTerminat ion()
If Thread.CurrentT hread Is m_thread Then
Throw New InvalidOperatio nException("Wai tForTermination
should not be called from the worker thread!")
End If
m_thread.Join()
End Sub

Public Sub CheckSuspend()
If Not Thread.CurrentT hread Is m_thread Then
Throw New InvalidOperatio nException("Che ckSuspend should
only be called from the worker thread!")
End If
m_event.WaitOne ()
End Sub

End Class

To see how it works try something like:

Private Sub Work()
For index As Integer = 1 To 50
Worker.CurrentW orker.CheckSusp end()
Debug.WriteLine (index, Worker.CurrentW orker.Name)
Dim value As Double = DirectCast(Work er.CurrentWorke r.Arg,
Double)
Thread.Sleep(Ti meSpan.FromSeco nds(value))
Next
End Sub

Public Sub Main()
Dim worker1 As New Worker(AddressO f Work, 0.25, "worker1")
Dim worker2 As New Worker(AddressO f Work, 0.5, "worker2")
Dim worker3 As New Worker(AddressO f Work, 0.75, "worker3")

Debug.WriteLine ("Pausing 5 seconds", "Main")
Thread.Sleep(Ti meSpan.FromSeco nds(5))
worker1.Suspend ()

Debug.WriteLine ("Pausing 5 seconds", "Main")
Thread.Sleep(Ti meSpan.FromSeco nds(5))
worker2.Suspend ()

Debug.WriteLine ("Pausing 5 seconds", "Main")
Thread.Sleep(Ti meSpan.FromSeco nds(5))
worker3.Suspend ()

Debug.WriteLine ("Pausing 1 seconds", "Main")
Thread.Sleep(Ti meSpan.FromSeco nds(1))

worker1.Resume( )
worker2.Resume( )
worker3.Resume( )

Debug.WriteLine ("Waiting for Termination", "Main")
worker1.WaitFor Termination()
worker2.WaitFor Termination()
worker3.WaitFor Termination()

End Sub

The above sample was posted in a thread titled "Technique for Pausing
Worker Thread" in this newsgroup between 21 Jan 2005 & 23 Jan 2005.

Hope this helps
Jay
"juky" <ju*******@yaho o.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
Hi all,

I have 3 running threads chencking for something in my application.
Based on that I need to stop some of them safely wait for something
else and restart. Sleep is not good in my case because i don't know how
much to wait. How and from where I can put a thread in pause an restart
it?

Thank you
Juky
Sub main ()
....
t1 = New Threading.Threa d(AddressOf Check1)
t1.Start()
t2 = New Threading.Threa d(AddressOf Check2)
t2.Start()
t3 = New Threading.Threa d(AddressOf Check3)
t3.Start()
end sub

sub Check1()
while true
"IF CHECK=TRUE THEN I HAVET TO SUSPEND THIS THREAD
end while
end Sub

sub Check2()
while true
"IF CHECK=TRUE THEN I HAVET TO SUSPEND THIS THREAD
end while
end Sub

sub Check3()
while true
"IF CHECK=TRUE THEN I HAVET TO SUSPEND THIS THREAD
end while
end Sub


Nov 21 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3173
by: Niel | last post by:
Hello friends, I think this issue has been posted before but i have not been able to get any solution that is why i am posting it again in detail as to what exactly is happneing in my case. Hope i will get solution this time. Any help would be appreciated. Now we are building dynamic websites. The Operating system that we have is Windows 2000(not Advanced server not Profession), it just says
0
1868
by: r_obert | last post by:
Hello, I'm trying to create a worker thread for my VC++ program, and was wondering whether I should be linking with the Multithread /MT or Multithread DLL /MD option? I'm not quite sure, in layman's terms, what the difference is. When I build with Multithread DLL, the linker complains about not being able to find a bunch of "unresolved external symbols" associated with nafxcwd.lib.
1
14389
by: stash | last post by:
When I stop all DB2 services on our Unix box - I still can see the following two DB2 processes running: root 20410 1 0 Oct 28 - 4:16 /usr/opt/db2_08_01/bin/db2fmcd db2as 21780 1 0 Oct 28 - 0:11 /home/ovenbird02/app/db2/das/bin/db2fmd -i db2as -m /home/ovenbird02/app/db2/das/lib/libdb2dasgcf.a So I have entered DB2STOP and DB2ADMIN STOP - and still the above two
4
7092
by: zbcong | last post by:
Hello: I write a multithread c# socket server,it is a winform application,there is a richtextbox control and button,when the button is click,the server begin to listen the socket port,waiting for a incoming connection,the relative code snipprt as following:: private IPAddress myIP=IPAddress.Parse("127.0.0.1"); private IPEndPoint myServer; private Socket socket; private Socket accSocket; private System.Windows.Forms.Button button2;...
1
9808
by: Primera | last post by:
I have an application that fixes some common problems that prevent the SMS Advanced Client from operating correctly. During this application I need to stop the Windows Management Instrumentation (winmgmt) service, delete the Repository directory, and then restart winmgmt which will then automatically regenerate the Repository directory. Since I am stopping WMI I cannot use System.Management to perform this. I have tried: ...
7
7236
by: shai | last post by:
I am working at .net 1.1, writing in c#. I have windows service with a COM object. Every unexpected time The COM object throw an error that make my service get stuck (do not respond). I can catch this error. I want to restart my windows service every time the COM object throws an error. I use System.ServiceProcess.ServiceController to stop and start my service. But there is one thing I do not understand:
0
2208
by: Emanuele | last post by:
I have write a program using MS Visual studio C++ 7.0 (platform Windows XP professional). I'm not using .NET. This program save data in a SQL server 2000 database using ADO. Everything works correctly, yet if i stop the sql service and then restart it, while the programs write records, the reconnection to the server dont't work. When the service stops i catch all the exceptions. I want try to reconnect to the database continually till...
2
5310
by: tikcireviva | last post by:
Hi Guys, I've done a mulithread queue implementation on stl<queue>, my developement environment is on VC6 as well as FC3. Let's talks about the win32 side. The suspected memory leak is find after I've run through my unit test cases. Test Case:
1
5670
by: aj | last post by:
A few service stop/start/restart questions on SQL Server 2005 SP2, which I'll call SQLS. It looks as if there are *potentially* 6 ways to start/stop SQLS Services like the engine itself, integration services, reporting service, Agent.. -SQLS Configuration Manager -SQLS Surface Area Configuration (for Services and Connections) -Mgmt Studio Local (on server)
0
9595
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10604
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10359
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10101
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9177
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7643
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6870
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3837
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3005
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.