Cyclone
Cyclone

Reputation: 18295

Dividing work into multiple threads

I've read a lot of different questions on SO about multithreaded applications and how to split work up between them, but none really seem to fit what I need for this. Here's how my program currently basically works:

Module Module1
'string X declared out here
    Sub Main()
'Start given number of threads of Main2()
    End Sub
    Sub Main2()
'Loops forever
'Call X = nextvalue(X), display info as needed
    End Sub
    Function nextvalue(byval Y as string)
'Determines the next Y in the sequence
    End Function
End Module

This is only a rough outline of what actually happens in my code by the way.

My problem being that if multiple threads start running Main2(), they're dealing with the same X value as in the other threads. The loop inside of main2 executes multiple times per millisecond, so I can't just stagger the loops. There is often duplication of work done.

How can I properly divide up the work so that the two threads running simultaneously never have the same work to run?

Upvotes: 1

Views: 1031

Answers (3)

yoozer8
yoozer8

Reputation: 7489

Use a lock so that only one thread can access X at a time. Once one thread is done with it, another thread is able to use it. This will prevent two threads from calling nextvalue(x) with the same value.

Upvotes: 1

Brian Gideon
Brian Gideon

Reputation: 48949

You should synchronize the generation and storage of X so that the composite operation appears atomic to all threads.

Module Module1

  Private X As String
  Private LockObj As Object = New Object()

  Private Sub Main2()

    Do While True

      ' This will be used to store a snapshot of X that can be used safely by the current thread.
      Dim copy As String

      ' Generate and store the next value atomically.
      SyncLock LockObj
        X = nextValue(X)
        copy = X
      End SyncLock

      ' Now you can perform operations against the local copy.
      ' Do not access X outside of the lock above.
      Console.WriteLine(copy)

    Loop

  End Sub

End Module

Upvotes: 2

Jon Raynor
Jon Raynor

Reputation: 3892

A thread manager is required to manage the threads and the work that they do. Say it is desirable to split up the work into 10 threads.

  1. Start the manager
  2. Manager creates 10 threads
  3. Assign work to the manager (queue up the work, let's say it queues up 10000 work items)
  4. Manager assigns a work item to complete for each of the 10 threads.
  5. As threads finish thier work, they report back to the manager that they are done and recieve another work item. The queue of work should be thread safe so that items can be enqueued and dequeued. The manager handles the management of work items. The threads just execute the work.

Once this is in place, work items should never be duplicated amongst threads.

Upvotes: 1

Related Questions