首页 \ 问答 \ 在Java中将工作负载动态分配到多个线程(Dynamically distributing workload to multiple threads in Java)

在Java中将工作负载动态分配到多个线程(Dynamically distributing workload to multiple threads in Java)

假设我有5个线程,必须为并行蒙特卡罗方法程序总共进行1,000,000函数调用。 我为5个线程中的每个线程分配了1,000,000 / 5函数调用。 然而,经过多次测试(一些测试范围高达1万亿次迭代),我意识到有些线程的完成速度比其他线程快得多。 因此,我想动态地为每个线程分配工作负载。 我的第一种方法涉及一个AtomicLong变量,它被设置为初始值,比方说,10亿。 在每个函数调用之后,我会将AtomicLong递减1.在每个函数调用之前,程序会检查AtomicLong是否大于0 ,如下所示:

AtomicLong remainingIterations = new AtomicLong(1000000000);
ExecutorService threadPool = Executors.newFixedThreadPool(5);

for (int i = 0; i < 5; i++) {//create 5 threads
   threadPool.submit(new Runnable() {
       public void run() {
          while (remainingIterations.get() > 0) {//do a function call if necessary 
             remainingIterations.decrementAndGet();//decrement # of remaining calls needed
             doOneFunctionCall();//perform a function call
          }
       }
   });
}//more unrelated code is not show (thread shutdown, etc.)

这种方法似乎非常慢,我正确使用AtomicLong吗? 有更好的方法吗?


Let's say I have 5 threads that must make a combined total of 1,000,000 function calls for a parallel Monte Carlo Method program. I assigned 1,000,000 / 5 function calls for each of the 5 threads. However, after many tests (some tests ranging up to 1 trillion iterations) I realized that some threads were finishing much faster than others. So instead I would like to dynamically assign workload to each of these threads. My first approach involved a AtomicLong variable that was set to an initial value of, let's say, 1 billion. After each function call, I would decrement the AtomicLong by 1. Before every function call the program would check to see if the AtomicLong was greater than 0, like this:

AtomicLong remainingIterations = new AtomicLong(1000000000);
ExecutorService threadPool = Executors.newFixedThreadPool(5);

for (int i = 0; i < 5; i++) {//create 5 threads
   threadPool.submit(new Runnable() {
       public void run() {
          while (remainingIterations.get() > 0) {//do a function call if necessary 
             remainingIterations.decrementAndGet();//decrement # of remaining calls needed
             doOneFunctionCall();//perform a function call
          }
       }
   });
}//more unrelated code is not show (thread shutdown, etc.)

This approach seemed to be extremely slow, am I using AtomicLong correctly? Is there a better approach?


原文:https://stackoverflow.com/questions/39734670
更新时间:2022-11-27 08:11

最满意答案

对于新窗口,可能类似于SW_SHOWNA / SWP_NOACTIVATE?


int HandledWidget::showPopup()
{
    int nRet(-1);

    show(SW_SHOWNOACTIVATE);

    BOOL bMenuDestroyed(FALSE);
    BOOL bMsgQuit(FALSE);
    HWND m_hWndOwner = GetWindow(m_hWnd, GW_OWNER);
    assert(GetForegroundWindow() == m_hWndOwner);

    while(TRUE)
    {
        if(GetProp(m_hWnd, MENU_EXIT_NOTIFY) != 0)
        {
            nRet = (int)GetProp(m_hWnd, MENU_EXIT_COMMAND_ID);
            break;
        }

        if(GetActiveWindow() != m_hWndOwner)
        {
            break;
        }

        m_bIsPopingUp = true;

        MSG msg = {0};
        if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            if(msg.message == WM_KEYDOWN
                || msg.message == WM_SYSKEYDOWN
                || msg.message == WM_KEYUP
                || msg.message == WM_SYSKEYUP
                || msg.message == WM_CHAR
                || msg.message == WM_IME_CHAR
                || msg.message == WM_MOUSEWHEEL
                )
            {
                //transfer the message to menu window
                msg.hwnd = m_hWnd;
            }
            else if(msg.message == WM_LBUTTONDOWN
                || msg.message == WM_RBUTTONDOWN
                || msg.message == WM_NCLBUTTONDOWN
                || msg.message == WM_NCRBUTTONDOWN)
            {
                //click on other window
                if(msg.hwnd != m_hWnd)
                {
                    m_bIsPopingUp = false;
                    DestroyWindow(m_hWnd);
                    bMenuDestroyed = TRUE;
                }
            }
            else if(msg.message == WM_QUIT)
            {
                bMsgQuit = TRUE;
            }

            TranslateMessage (&msg);
            DispatchMessageW (&msg);
        }
        else
        {
            MsgWaitForMultipleObjects (0, 0, 0, 10, QS_ALLINPUT);
        }

        if(bMenuDestroyed) break;

        if(bMsgQuit)
        {
            PostQuitMessage(msg.wParam);
            break;
        }
    }

    m_bIsPopingUp = false;

    if(!bMenuDestroyed) DestroyWindow(m_hWnd);

    return nRet;
}

bool HandledWidget::exitPopup(int nCommandId)
{
    BOOL bRet = SetProp(m_hWnd, MENU_EXIT_NOTIFY, (HANDLE)1);
    SetProp(m_hWnd, MENU_EXIT_COMMAND_ID, (HANDLE)nCommandId);
    return bRet;
}

and handle wm_mouseactivate:

LRESULT ComboxList::onMouseActivate( WPARAM wParam, LPARAM lParam, bool &bHandled )
{
    bHandled = true;
    return MA_NOACTIVATE;
}

remember do not activate the new window using SetFocus/SetWindowPos(SW_SHOWWINDOW)/ShowWindow(SW_SHOW)/SetActivate/SetForegroundWindow etc.

Then you get a non-activate window just like the system menu.

reference:http://www.cppblog.com/weiym/archive/2013/04/07/199189.html

相关问答

更多
  • 它肯定确实看起来这是Cocoa应该自动执行的。 我不知道它是否确实,但首先要检查的是窗口控制器是否正确连接到他们的文档。 你的文档子类的windowControllers属性是否包含所有正确的对象? 如果这样做不好,那么从NSWindow的参考看来,阻止其标题被添加到Windows菜单中的窗口的唯一方法是-[NSWindow setExcludedFromWindowsMenu:] 。 看起来你需要在所有窗口中调用它,然后设置一个对象(可能在MainMenu nib中),该对象负责所有窗口的位置并在Wind ...
  • 我有同样的问题。 当WPF窗口的本机Win32窗口没有与之关联的图标时, WS_EX_DLGMODALFRAME似乎只删除图标。 WPF(方便地)使用应用程序的图标作为所有窗口的默认图标,而没有明确设置的图标。 通常情况下,这不会导致任何问题,并且可以省去在每个窗口上手动设置应用程序图标的麻烦。 但是,当我们尝试删除图标时,它会给我们带来问题。 由于问题是WPF自动为我们设置窗口的图标,我们可以在应用WS_EX_DLGMODALFRAME时将WS_EX_DLGMODALFRAME发送到Win32窗口以重置其 ...
  • 如果我已经很好地理解了你,你会打开每个病人的日历清单的正确过滤,但问题是,当你点击这些记录中的任何一个时,它什么也不做,你需要打开日历窗体视图。 如果是这样,请在按钮中指定您还希望打开calendrier模型的表单视图,而不是树视图: @api.multi def btnVoirCalendriers(self): self.ensure_one() return { 'type' : 'ir.actions.act_window', 'res_mod ...
  • 基于Firefox源代码,我开发了以下代码来解决我的问题: HMENU hMenu = GetSystemMenu(hWnd, FALSE); if (hMenu) { MENUITEMINFO mii; mii.cbSize = sizeof(MENUITEMINFO); mii.fMask = MIIM_STATE; mii.fType = 0; // update the options mii.fState = MF_ENABLED; Se ...
  • 没有带烘焙的winapi功能来显示系统菜单。 您可以使用pinvoke自己显示它。 GetSystemMenu()函数返回系统菜单的句柄,使用TrackPopupMenu()显示它,通过调用SendMessage执行所选命令以发送WM_SYSCOMMAND。 一些示例代码显示了如何执行此操作并包含必要的声明: using System.Runtime.InteropServices; ... private void Window_MouseDown(object sender, MouseButt ...
  • 如果我没有弄错的话,无边界窗口会被标记为不提供系统菜单,并且它不会出现在任务栏中。 任何给定窗口没有边框但未出现在任务栏中的事实是窗口上设置的样式标志的结果。 可以使用GetWindowLong和SetWindowLong API调用设置这些特定的Style标志。 但是你必须要小心,因为某些样式不能一起工作。 多年来,我已经编写了许多自定义控件,并且我一直在哄骗窗口,以成为他们原本不打算成为的东西。 例如,我已经编写了自己的下拉控件,我需要一个窗口来表现为弹出窗口而不是激活。 以下代码将执行此操作。 请注意 ...
  • ir.actions.act_window模型上的views字段是一个非存储的计算字段,没有反函数。 换句话说,它是只读的,甚至不存储在数据库中。 这就是为什么当您使用此字段创建新操作时,它不会保存,只会被忽略。 文档有点令人困惑(我也很难解决这个问题),但技术上并没有错。 这个字段确实是(view_id, view_type)对的列表,你只是在处理存储在数据库中的动作时不能直接改变它。 它是基于view_id和view_ids字段自动生成的。 但是,您可以直接将该字段用于未存储在数据库中但从python代 ...
  • 对于新窗口,可能类似于SW_SHOWNA / SWP_NOACTIVATE? int HandledWidget::showPopup() { int nRet(-1); show(SW_SHOWNOACTIVATE); BOOL bMenuDestroyed(FALSE); BOOL bMsgQuit(FALSE); HWND m_hWndOwner = GetWindow(m_hWnd, GW_OWNER); assert(GetForegroundW ...
  • 感谢Raymond Chen和Jonathan Potter的评论,这里有一个功能: function PopupMenusRightAligned(): Boolean; var res: Integer; begin SystemParametersInfo(SPI_GetMenuDropAlignment, 0, @res, 0); Result := res=0; end; API文档: https : //msdn.microsoft.com/ms724947 Thanks to the ...
  • 我假设你从未调用MainMenu屏幕的创建方法。 所以stage没有初始化并抛出NullPointer异常。 使用show方法初始化屏幕变量。 As I assume you never called create method of MainMenu screen. so stage is not initialized and throw NullPointer exception. use show method for initialization of your screen variable.

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。