まさるblog

越後在住子持ちプログラマー奮闘記 - Author:まさる(高野 将、TAKANO Sho)

目次

Blog 利用状況

ニュース

著書

2010/7発売


Web掲載記事

@IT

.NET開発を始めるVB6プログラマーが知るべき9のこと

CodeZine

実例で学ぶASP.NET Webフォーム業務アプリケーション開発のポイント

第1回 3層データバインドを正しく活用しよう(前編)

ブログパーツ


書庫

日記カテゴリ

コミュニティ

VBでProducer/Consumerパターン

ネタ元:生産者 と 消費者

 

#勝手にportしちゃうぞ企画第2段w

 

今回はMSDNライブラリ「方法 : producer スレッドと consumer スレッドを同期する (C# プログラミング ガイド)」のコードをVBにportしました。

VBに変換する際気を付けるのは、以下のような点。

  • lockステートメントはSyncLock
  • 配列の初期化方法が違う

 

コードは以下の通り。

Imports System.Threading

Public Class SyncEvents
	Private _newItemEvent As EventWaitHandle
	Public ReadOnly Property NewItemEvent() As EventWaitHandle
		Get
			Return _newItemEvent
		End Get
	End Property

	Private _exitThreadEvent As EventWaitHandle
	Public ReadOnly Property ExitThreadEvent() As EventWaitHandle
		Get
			Return _exitThreadEvent
		End Get
	End Property

	Private _eventArray As WaitHandle()
	Public ReadOnly Property EventArray() As WaitHandle()
		Get
			Return _eventArray
		End Get
	End Property

	Public Sub New()
		_newItemEvent = New AutoResetEvent(False)
		_exitThreadEvent = New ManualResetEvent(False)
		_eventArray = New WaitHandle() {_newItemEvent, _exitThreadEvent}
	End Sub
End Class

Public Class Producer
	Private _queue As Queue(Of Integer)
	Private _syncEvents As SyncEvents

	Public Sub New(ByVal q As Queue(Of Integer), ByVal e As SyncEvents)
		_queue = q
		_syncEvents = e
	End Sub

	Public Sub ThreadRun()
		Dim count As Integer = 0
		Dim r As New Random()
		While Not _syncEvents.ExitThreadEvent.WaitOne(0, False)
			SyncLock DirectCast(_queue, ICollection).SyncRoot
				While _queue.Count < 20
					_queue.Enqueue(r.Next(0, 100))
					_syncEvents.NewItemEvent.Set()
					count += 1
				End While
			End SyncLock
		End While
		Console.WriteLine("Producer thread: produced {0} items", count)
	End Sub
End Class

Public Class Consumer
	Private _queue As Queue(Of Integer)
	Private _syncEvents As SyncEvents

	Public Sub New(ByVal q As Queue(Of Integer), ByVal e As SyncEvents)
		_queue = q
		_syncEvents = e
	End Sub

	Public Sub ThreadRun()
		Dim count As Integer = 0
		While WaitHandle.WaitAny(_syncEvents.EventArray) <> 1
			SyncLock DirectCast(_queue, ICollection).SyncRoot
				Dim item As Integer = _queue.Dequeue()
				count += 1
			End SyncLock
		End While
		Console.WriteLine("Consumer thread: consumed {0} items", count)
	End Sub
End Class

Public Class Program
	Private Shared Sub ShowQueueContents(ByVal q As Queue(Of Integer))
		SyncLock DirectCast(q, ICollection).SyncRoot
			For Each item As Integer In q
				Console.Write("{0} ", item)
			Next
		End SyncLock
		Console.WriteLine()
	End Sub

	Public Shared Sub Main()
		Dim queue As New Queue(Of Integer)
		Dim syncEvent As New SyncEvents()

		Console.WriteLine("Configuring worker threads...")

		Dim producer As New Producer(queue, syncEvent)
		Dim cunsumer As New Consumer(queue, syncEvent)

		Dim producerThread As New Thread(AddressOf producer.ThreadRun)
		Dim consumerThread As New Thread(AddressOf cunsumer.ThreadRun)

		Console.WriteLine("Launching producer and consumer threads...")

		producerThread.Start()
		consumerThread.Start()

		For i As Integer = 0 To 3
			Thread.Sleep(2500)
			ShowQueueContents(queue)
		Next i

		Console.WriteLine("Signaling threadds to terminate...")

		syncEvent.ExitThreadEvent.Set()

		producerThread.Join()
		consumerThread.Join()
	End Sub
End Class

投稿日時 : 2009年9月16日 22:31

Feedback

# re: VBでProducer/Consumerパターン 2009/09/16 22:38 επιστημη

"VBでもやったるわー"て意気込んではみたものの、
SyncLockを見つけきれずにディスクの隅っこに
うっちゃらかしてるのは内緒♪

# re: VBでProducer/Consumerパターン 2009/09/16 22:43 まさる

SyncLockさえ分かれば、あとはほとんど違いませんものねー

# re: VBでProducer/Consumerパターン 2009/09/17 12:14 とっちゃん

こ、これは...次は Native C++?w

# re: VBでProducer/Consumerパターン 2009/09/17 17:01 かたぎり

SyncLockって、こっからここまで、
ちゃんと順番に処理やでぇ、的に便利。
見た目でもわかるし。

変数一個だけならInterLock使っちゃえ的になっちゃう。
危険なお気楽かもだけどw

# re: VBでProducer/Consumerパターン 2009/09/18 5:22 まさる

>こ、これは...次は Native C++?w

ごめんわがんねw

>変数一個だけならInterLock使っちゃえ的になっちゃう。

これは「Interlockedクラス」のことでいいでしょか?
http://msdn.microsoft.com/ja-jp/library/system.threading.interlocked.aspx

変数の値を設定する際、スレッド・セーフにしてくれるクラスってことでいいのかな?
こんなのは知らんかったので勉強になります。

# pHsnJdJmoDevMp 2011/12/23 0:12 http://247options.com/

As I have expected, the writer blurted out..!

# bTOLQkjlpofNxE 2011/12/23 18:26 http://247options.com/

Yeah !... life is like riding a bicycle. You will not fall unless you stop pedaling!!...

# AgiOoZnhkBvRRhA 2014/08/28 7:53 http://crorkz.com/

1A9FvF It's actually a cool and useful piece of information. I'm glad that you shared this useful info with us. Please keep us informed like this. Thanks for sharing.

# SoeKpKSFmZqHXvwSoB 2022/04/19 12:40 johnansaz

http://imrdsoacha.gov.co/silvitra-120mg-qrms

タイトル
名前
Url
コメント