c# - 具有唯一连续值的线程安全方式

标签 c# multithreading thread-safety

我有这样的代码:

static volatile int i = 0;
static void Foo() {
int myInt = i++;
// now use myInt
}

我需要让 myInt 的每个值都唯一且连续。例如,如果要运行 5 个这样的线程,它们的 myInt 值应该是 0, 1, 2, 3, 4(顺序不重要)。

所以,我不想知道这种方式是否是线程安全的,实现我需要的最佳方式是什么?

最佳答案

线程安全使用Interlocked.Increment() :

Increments a specified variable and stores the result, as an atomic operation.

    int MyInt = Interlocked.Increment(ref i);

[...并且没有理由标记为 volatile,它有些损坏并且可能在未来的 C# 版本中被弃用/删除 ...]

关于c# - 具有唯一连续值的线程安全方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6421941/

相关文章:

python - Python 线程有问题吗?

c++ - 当 pthreads 在 mutex_lock/cond_wait 中等待时会发生什么?

asp.net - 缓解 Web 服务器上的 RsaCryptoServiceProvider 线程安全问题

c# - 删除十进制数中的零值有困难吗?

c# - 异步任务 'Clogging'

python - 使用线程向不同网站发出 GET 请求然后发出 POST 请求时遇到问题

thread-safety - Kotlin 单例线程安全吗?

c#-4.0 - Task.ContinueWith 线程安全吗?

c# - C# 应用程序中的本地化

c# - 是否可以从后面的代码编辑元描述?