跨多个线程管理状态



我有一个带有一堆序列的 F# 类。该类包含一个简单的next()方法,该方法返回当前序列中的下一个元素。如果当前序列的所有元素都已返回,它将改为移动到下一个序列。该类包含一个指针,该指针是序列中的下一个元素以及它从哪个序列返回。

我目前仅限于公开next()方法。

一些上游类将在不同的线程之间使用 my 类(相同的对象实例)。这将使该点不同步,因为多个线程都应该从头开始。我知道这并不理想,但这是我目前必须处理的。

例:

Thread 1 next(): return elem. A Thread 1 next(): return elem. B Thread 2 next(): return elem. A Thread 1 next(): return elem. C Thread 2 next(): return elem. B

有没有办法跟踪每个线程的指针?

我一直在考虑使用Threading.Thread.CurrentThread.ManagedThreadId作为 Map 中的键,然后返回指针(并相应地更新它)。我有点担心这个 Map 的线程安全性,以及两个线程是否同时更新其状态。

我希望 somone 能为我提供一些关于如何让它工作的想法。

这可以通过使用MailboxProcessor来管理状态,然后使用类从使用者中抽象MailboxProcessor来实现。 如果您在多个线程之间共享实例,它们将以线程安全的方式看到彼此的更新。 如果为每个线程使用专用实例,则它们只会看到自己的更新。 其代码如下所示:

// Add whatever other commands you need
type private SequenceMessage = Next of AsyncReplyChannel<int>
type IntSequence() =
let agent = MailboxProcessor<SequenceMessage>.Start
<| fun inbox ->
let rec loop state =
async {
let! message = inbox.Receive()
// Add other matches as requried
match message with
| Next channel -> 
let newState = state + 1
channel.Reply(newState)
return! loop newState
}
loop 0
let next () =
agent.PostAndReply <| fun reply -> Next reply
let asyncNext () =
agent.PostAndAsyncReply <| fun reply -> Next reply
member __.Next () = next ()
member __.AsyncNext () = asyncNext ()

然后,要以每个线程看到来自其他线程的更新的方式使用它,您将执行等效的操作:

// To share state across multiple threads, use the same instance
let sequence = IntSequence()
[1..10]
|> List.map (fun _ -> sequence.AsyncNext())
|> Async.Parallel
|> Async.RunSynchronously
|> Array.iter (fun i -> printfn "%d" i)

哪些打印:

1
2
3
4
5
6
7
8
9
10

要以每个线程只看到自己的更新的方式使用它,您只需将前面的示例更改为如下所示:

// To use a dedicate state for each thread, create a new instance
[1..10]
|> List.map (fun _ -> IntSequence())
|> List.map (fun sequence -> sequence.AsyncNext())
|> Async.Parallel
|> Async.RunSynchronously
|> Array.iter (fun i -> printfn "%d" i)

哪些打印:

1
1
1
1
1
1
1
1
1
1

最新更新