假设我有一个天真的阶乘函数:
import java.util.stream.LongStream;
public class FactorialTest {
static long factorial(long n, boolean parallel) {
return (parallel
? LongStream.range(1, n).parallel()
: LongStream.range(1, n))
.reduce(1, (l, m) -> l * m);
}
public static void main(String[] args) {
System.out.println(factorial(10, true));
}
}
Run Code Online (Sandbox Code Playgroud)
我觉得即使在单逻辑核心机器上,多线程减少仍然比单线程更快.如何使用流API对其进行测试或解决此问题?
有没有办法在控制台应用程序中使用tasks/await而应用程序终止于await语句?以下不在主要方法范围内.它属于一个单独的类.主叫它.我研究了一下,看了一篇关于使用manualresetevent的文章,但是当我尝试将这个逻辑插入到这个类中时,它没有什么区别,它永远不会超越等待.它刚关闭.
Task Taskone = Task.Run(() => (threadOne.checkData(numberArray,archivePath,dirone,dirtwo, ref missingoneList)));
Task Tasktwo = Task.Run(() => (threadTwo.checkAll(numberArray, archivePath, dirone, dirtwo, ref missingtwoList)));
Task Taskthree = Task.Run(() => (threadThree.checkCnt(numberArray, archivePath, dirone, dirtwo, ref missingthreeList)));
await Task.WhenAll(Taskone,Tasktwo,Taskthree);
Console.WriteLine("all tasks have completed");
Run Code Online (Sandbox Code Playgroud)
先感谢您.
我正在尝试使用Java 8的parallelStream()并行执行几个长时间运行的请求(例如Web请求).简化示例:
List<Supplier<Result>> myFunctions = Arrays.asList(() -> doWebRequest(), ...)
List<Result> results = myFunctions.parallelStream().map(function -> function.get()).collect(...
Run Code Online (Sandbox Code Playgroud)
因此,如果有两个函数分别阻塞2秒和3秒,我希望在3秒后得到结果.然而,它确实需要5秒钟 - 即似乎函数按顺序执行而不是并行执行.难道我做错了什么?
编辑:这是一个例子.当我想要它〜2000时,花费的时间是~4000毫秒.
long start = System.currentTimeMillis();
Map<String, Supplier<String>> input = new HashMap<String, Supplier<String>>();
input.put("1", () -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "a";
});
input.put("2", () -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "b";
});
Map<String, String> results = input.keySet().parallelStream().collect(Collectors.toConcurrentMap(
key -> key,
key -> {
return input.get(key).get();
}));
System.out.println("Time: " …Run Code Online (Sandbox Code Playgroud) 我最近发布了另一个问题,关于如何处理数据库中的项目列表,如果进程失败,则重试3次.
问题可以在这里找到:C#处理循环中的大项目列表,如果失败则重试
我对这个问题的答案做了一些修改,这里是代码:
我有一个继承ApiController类的抽象类,我的所有Web Api控制器都继承了ApiBaseController:
在ApiBaseController我已经定义了使用Repository模式的UnitOfWork以便CRUD SQL数据库.UnitOfWork和存储库模式工作正常,我测试了它,我没有遇到任何问题.
public abstract class ApiBaseController : ApiController
{
protected UnitOfWork Uow { get; set; }
protected override void Dispose(bool disposing)
{
if (Uow != null && Uow is IDisposable)
{
((IDisposable)Uow).Dispose();
Uow = null;
}
base.Dispose(disposing);
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我有一个JobController继承ApiBaseController继承的东西ApiController,使其成为Web Api控制器.
该控制器有一个端点api/endpoint/sendrequests,当被调用时,它将Jobs从数据库中获取所有数据并以10个批次处理它们.
该方法ProcessTaskAsync将处理从数据库检索的每个单独任务,如果它失败,那么它将尝试再处理2次,直到该任务被忽略.
除了在ProcessTaskAsync处理任务之后我尝试使用UnitOfWork将任务的结果保存到数据库之外,一切都工作得很好await Uow.Results.AddAsync(result);.在这里它失败了!问题是Uow对象是null,我不明白为什么.我的想法是因为任务是异步处理的,控制器执行结束意味着控制器被处理,因此UnitOfWork.
知道为什么Uow是null并且我该如何解决这个问题?
[AllowAnonymous]
[RoutePrefix("api/endpoint")] …Run Code Online (Sandbox Code Playgroud) 经过Stack Overflow上的大量帖子后,我想我能够提出一个线程安全版本的List,这肯定不符合Concurrent集合的水平,因为它使用了ReaderWriterLockSlim,但在我的理解中,它与简单的锁定版本相比,它可以按预期工作并具有更好的性能.您可能认为的任何内容都可以在当前的实现中得到改进.它仍然没有实现List的所有功能,因为我刚刚处理了IList
免责声明 - 我从Stack Overflow中得到了一些想法,所以它肯定包含来自不同帖子的点点滴滴
修改 - 修改代码以处理某些情况,这些情景在上次通信中发布,如:
if(list.count > 0)
return list[0]
Run Code Online (Sandbox Code Playgroud)
作为偏离主题,没有理由将此标记为暂停
线程安全实现
using System.Collections.Generic;
using System.Threading;
/// <summary>
/// Thread safe version of the List using
/// </summary>
/// <typeparam name="T"></typeparam>
public class ThreadSafeListWithRWLock<T> : IList<T>
{
private List<T> internalList;
private readonly ReaderWriterLockSlim rwLockList;
public ThreadSafeListWithRWLock()
{
internalList = new List<T>();
rwLockList = new ReaderWriterLockSlim();
}
// Other Elements of IList implementation
public IEnumerator<T> GetEnumerator()
{
return Clone().GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return Clone().GetEnumerator();
}
public …Run Code Online (Sandbox Code Playgroud) .net c# parallel-processing multithreading task-parallel-library
这是我目前的代码:
Parallel.ForEach(Arguments, Argument =>
{
if (Argument != Command_Name)
{
WebRequest web_request = WebRequest.Create("https://www.aol.com/?command=1&domain=" + Argument);
web_request.Timeout = 5000;
((HttpWebRequest)web_request).UserAgent = "Mozilla Firefox 5.0";
HttpWebResponse web_response = (HttpWebResponse)web_request.GetResponse();
StreamReader response = new StreamReader(web_response.GetResponseStream(), Encoding.UTF8);
Message += Argument + " => " + response.ReadToEnd() + Environment.NewLine;
}
});
Run Code Online (Sandbox Code Playgroud)
此代码无法正常工作,我正在寻找一个小的替代品.此代码返回Message字符串中的一些参数...多线程字符串添加的好方法是什么?这就是我需要的.
更多信息:消息字符串有时会返回a,b和c,而其他消息字符串只返回a或b ...
感谢您的帮助,谢谢!
我已经在这个网站上看到了几个关于这个问题的帖子.但是,我认为我的严格代码由于创建线程而产生的开销并且所有这些都不应该是一个大问题,现在开放的mp变得慢得多!我正在使用带有gfortran 4.6.3的四核机器作为我的编译器.以下是测试代码的示例.
Program test
use omp_lib
integer*8 i,j,k,l
!$omp parallel
!$omp do
do i = 1,20000
do j = 1, 1000
do k = 1, 1000
l = i
enddo
enddo
enddo
!$omp end do nowait
!$omp end parallel
End program test
Run Code Online (Sandbox Code Playgroud)
如果我在没有打开mp的情况下运行它,此代码大约需要80秒,但是,打开mp,大约需要150秒.我在其他严肃的代码中看到了同样的问题,在串行模式下运行时间约为5分钟左右.在这些代码中,我注意到从线程到线程没有依赖关系.那么为什么这些代码变慢而不是更快?
提前致谢.
我正在使用遗传算法构建优化程序.我使用Parallel.For来减少时间.但它导致了一个问题,在下面的代码中是相同的:
class Program
{
static void Main(string[] args)
{
int j=0;
Parallel.For(0, 10000000, i =>
{
j++;
});
Console.WriteLine(j);
Console.ReadKey();
}
}
Run Code Online (Sandbox Code Playgroud)
每次我运行上面的程序时,它会在0到10000000之间写入不同的j值.我猜它不会等待所有迭代完成.它传递到下一行.我该怎么解决这个问题?任何帮助将不胜感激.谢谢.
版本:Interlocked.Increment(ref j); 子句解决了意外的结果,但是当我与正常循环比较时,此操作会导致大约10倍的时间.
我是并行编程的新手,我试图找出为什么偶尔会得到一个EmonitorLockException:当我增加要运行的并行任务的数量时,不拥有对象锁.是这样的情况,线程变得纠结我运行的任务越多.或者我的代码不正确?
{$APPTYPE CONSOLE}
uses
System.SysUtils, System.Threading, System.Classes, System.SyncObjs, System.StrUtils;
const
WorkerCount = 10000; // this is the number of tasks to run in parallel note:when this number is increased by repeated factors of 10
// it takes longer to produce the result and sometimes the program crashes
// with an EmonitorLockException:Object lock not owned . Is it that my program is not written correctly or efficiently to run
// a large number of parallel taks and the Threads become entagled. …Run Code Online (Sandbox Code Playgroud) c# ×5
java ×3
asynchronous ×2
java-8 ×2
.net ×1
async-await ×1
concurrency ×1
console ×1
delphi ×1
fortran ×1
java-stream ×1
openmp ×1
parallel.for ×1
string ×1
task ×1