Tag: multithreading

私人构造函数,以避免竞争条件

我正在阅读Java Concurrency in Practice会话4.3.5 @ThreadSafe public class SafePoint{ @GuardedBy("this") private int x,y; private SafePoint (int [] a) { this (a[0], a[1]); } public SafePoint(SafePoint p) { this (p.get()); } public SafePoint(int x, int y){ this.x = x; this.y = y; } public synchronized int[] get(){ return new int[] {x,y}; } public synchronized void set(int x, […]

为什么UncaughtExceptionHandler不能被ExecutorService调用?

我偶然发现了一个问题,可以概括如下: 当我手动创build线程(即通过实例化java.lang.Thread ) UncaughtExceptionHandler被适当地调用。 但是,当我用一个ThreadFactory使用ExecutorService处理程序是ommited。 我错过了什么? public class ThreadStudy { private static final int THREAD_POOL_SIZE = 1; public static void main(String[] args) { // create uncaught exception handler final UncaughtExceptionHandler exceptionHandler = new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { synchronized (this) { System.err.println("Uncaught exception in thread '" + t.getName() + "': […]

EF数据上下文 – asynchronous/等待和multithreading

我经常使用async / await来确保ASP.NET MVC Web API线程不被更长时间运行的I / O和networking操作阻塞,特别是数据库调用。 System.Data.Entity命名空间在这里提供了各种帮助器扩展,如FirstOrDefaultAsync , ContainsAsync , CountAsync等等。 但是,由于数据上下文不是线程安全的,这意味着下面的代码是有问题的: var dbContext = new DbContext(); var something = await dbContext.someEntities.FirstOrDefaultAsync(e => e.Id == 1); var morething = await dbContext.someEntities.FirstOrDefaultAsync(e => e.Id == 2); 事实上,我有时会看到例外,例如: System.InvalidOperationException:连接未closures。 连接的当前状态是打开的。 那么是否正确的模式使用单独的using(new DbContext…)块为每个asynchronous调用数据库? 那么执行同步操作可能会更有益吗?

使用AsParallel()/ Parellel.ForEach()指导方针?

寻求一些利用AsParallel()或者Parallel.ForEach()来加快速度的build议。 见下面的方法(这个例子简化/混蛋)。 它需要一个像“美国,法国,亚太地区”这样的名单,其中“亚太地区”可能是另外50个“美国,法国,日本,美国,英国等等”的别名。 方法应采取“美国,法国,亚太地区”,并将其转换为“美国”,“法国”,以及所有“亚太地区”国家的名单。 private IEnumerable<string> Countries (string[] countriesAndAliases) { var countries = new List<string>(); foreach (var countryOrAlias in countriesAndAliases) { if (IsCountryNotAlias(countryOrAlias)) { countries.Add(countryOrAlias); } else { foreach (var aliasCountry in AliasCountryLists[countryOrAlias]) { countries.Add(aliasCountry); } } } return countries.Distinct(); } 是不是把这个并行化就像把它改变成下面那样简单? 使用AsParallel()比这更多的细微差别? 我应该使用Parallel.ForEach()而不是foreach ? 并行化foreach循环时应使用什么经验法则? private IEnumerable<string> Countries (string[] countriesAndAliases) { var countries = […]

线程本地和内存泄漏

在多个post中提到:不恰当的使用ThreadLocal导致内存泄漏。 我正在努力了解如何使用ThreadLocal发生内存泄漏。 我唯一的想法是如下: 一个Web服务器维护一个线程池(例如servlet)。 如果ThreadLocal中的variables没有被删除,这些线程可能会造成内存泄漏,因为线程不会死亡。 这种情况下没有提到“Perm Space”内存泄漏。 这是内存泄漏的唯一(主要)用例吗?

“对易失性字段的引用不会被视为易变的”影响

下面的代码 using System.Threading; class Test { volatile int counter = 0; public void Increment() { Interlocked.Increment(ref counter); } } 引发以下编译器警告: "A reference to a volatile field will not be treated as volatile" 我在这里做错了什么来提出这个警告? 为什么编译器会提醒我呢?

在Python中正确使用互斥

我开始在Python中的multithreading(或者至less有可能是我的脚本创build多个线程)。 这个algorithm会是一个互斥量的正确用法吗? 我还没有testing这个代码,它可能不会工作。 我只想让processData在一个线程(一次一个)中运行,并且主要的while循环继续运行,即使队列中有一个线程。 from threading import Thread from win32event import CreateMutex mutex = CreateMutex(None, False, "My Crazy Mutex") while(1) t = Thread(target=self.processData, args=(some_data,)) t.start() mutex.lock() def processData(self, data) while(1) if mutex.test() == False: do some stuff break 编辑:重新读我的代码我可以看到,这是非常错误的。 但是,嘿,这就是为什么我在这里寻求帮助。

什么时候应该使用multithreading? 如果不同的线程执行相互独立的任务,multithreading将是有益的吗?

这是我昨天晚上被拒绝的采访中唯一不能回答的两个问题。

在C#中访问简单的布尔标志时,是否需要locking或标记为volatile?

让我们只是说你有一个简单的操作在后台线程上运行。 您想要提供取消此操作的方法,以便您创build一个布尔标志,您可以通过取消button的单击事件处理程序将其设置为true。 private bool _cancelled; private void CancelButton_Click(Object sender ClickEventArgs e) { _cancelled = true; } 现在,您正在从GUI线程设置取消标志,但是您正在从后台线程读取它。 访问布尔之前,你需要locking吗? 你需要这样做(显然locking在button单击事件处理程序): while(operationNotComplete) { // Do complex operation lock(_lockObject) { if(_cancelled) { break; } } } 还是可以接受这样做(没有locking): while(!_cancelled & operationNotComplete) { // Do complex operation } 或者如何将_cancelledvariables标记为volatile。 这是必要的吗? [我知道有BackgroundWorker类与它内置的CancelAsync()方法,但我对这里的locking和线程variables访问的语义和使用感兴趣,而不是具体的实现,代码只是一个例子。 似乎有两个理论。 1)因为它是一个简单的内置types(并且访问内置types在.net中是primefaces的),并且因为我们只是在一个地方写信给它,只能在后台线程上读取,所以不需要locking或标记为volatile。 2)你应该把它标记为volatile,因为如果你没有编译器可以优化while循环中的读取,因为它认为没有什么能够修改值。 哪一个是正确的技术? (为什么?) [编辑:这似乎有两个明确界定和反对的思想stream派。 我正在寻找一个明确的答案,所以请尽可能张贴您的理由,并引用您的来源与您的答案。

在调用condition_variable.notify_one()之前是否必须获取locking?

我对使用std::condition_variable有点困惑。 我知道我必须在调用condition_variable.wait()之前在mutex上创build一个unique_lock 。 我找不到在调用notify_one()或notify_all()之前是否也应该获取唯一的锁。 cppreference.com上的示例有冲突。 例如, notify_one页面给出了这个例子: #include <iostream> #include <condition_variable> #include <thread> #include <chrono> std::condition_variable cv; std::mutex cv_m; int i = 0; bool done = false; void waits() { std::unique_lock<std::mutex> lk(cv_m); std::cout << "Waiting… \n"; cv.wait(lk, []{return i == 1;}); std::cout << "…finished waiting. i == 1\n"; done = true; } void signals() { […]