multithreading,winapi,opengl,c++11 , Win32 Message Pump and std::thread Used to Create OpenGL Context and Render


Win32 Message Pump and std::thread Used to Create OpenGL Context and Render

Question:

Tag: multithreading,winapi,opengl,c++11

If I have a function that does the following:

bool foo::init()
{
    [Code that creates window]
    std::thread run(std::bind(&foo::run, this));

    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

Where run is defined as:

void foo::run()
{
    [Code that creates initial opengl context]
    [Code that recreates window based on new PixelFormat using wglChoosePixelFormatARB]
    [Code that creates new opengl context using wglCreateContextAttribsARB]

    do {
        [Code that handles rendering]
    } while (!terminate);   
}

Since the window is recreated on the rendering thread, and the message pump will be performed on the main thread is this considered safe? What function will the WndProc be called on? The above code could be considered bad design, but that is not what I am interested in. I am only interested in what is the defined behavior.


Answer:

A Win32 window is bound to the thread that creates it. Only that thread can receive and dispatch messages for the window, and only that thread can destroy the window.

So, if you re-create the window inside of your worker thread, then that thread must take over responsibility for managing the window and dispatch its messages.

Otherwise, you need to delegate the re-creation of the window back to your main thread so it stays in the same thread that originally created it.

bool foo::init()
{
    [Code that creates window]

    std::thread run(std::bind(&foo::run, this));

    while (GetMessage(&msg, NULL, 0, 0)) {
        if (recreate needed) {
            [Code that recreates window and signals worker thread]
            continue;
        }
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

void foo::run()
{
    [Code that creates initial opengl context]

    [Code that asks main thread to recreate window based on new PixelFormat using wglChoosePixelFormatARB, and waits for signal that the recreate is finished]

    [Code that creates new opengl context using wglCreateContextAttribsARB]

    do {
        [Code that handles rendering]
    } while (!terminate);   
}

Otherwise, call wglChoosePixelFormatARB() in the main thread before starting the worker thread, and store the chosen PixelFormat where the thread can access it.

bool foo::init()
{
    [Code that creates window]
    [Code that gets PixelFormat using wglChoosePixelFormatARB]

    std::thread run(std::bind(&foo::run, this));

    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

void foo::run()
{
    [Code that creates opengl context using wglCreateContextAttribsARB]

    do {
        [Code that handles rendering]
    } while (!terminate);   
}

Related:


How can we make a thread to sleep for a infinite time in java?


java,multithreading,thread-sleep
Pls help me to understand how can we make a thread to sleep for a infinite time period .

Guarantee TransformBlock output sequence


c#,multithreading,async-await,task-parallel-library,tpl-dataflow
From the TPL documentation As with ActionBlock<TInput>, TransformBlock<TInput,TOutput> defaults to processing one message at a time, maintaining strict FIFO ordering. However, in a multi-threaded scenario, i.e. if multiple threads are "simultaneously" doing SendAsync and then "awaiting" for a result by calling ReceiveAsync, how do we guarantee that the thread that...

How do you start a function at a certain time in Python?


python,multithreading,events,time,condition
I have a list of timestamps, and I need to call a specific method when those timestamps are reached. Those timestamps are roughly 20ms apart. At the moment I am using busy waiting in a separate thread, but I am worried about the CPU overload. Example : while True: if...

How does the kernel separate threads from processes


linux,multithreading,linux-kernel
Suppose I have a browser process like Firefox, that has pid = 123. Firefox has 5 opened tabs each running in a separate thread, so in total it has 5 threads. So I want to know in depth, how the kernel will separate the process into the thread to execute...

EntityFramework 6 / SqlCe 4 SaveChangesAsync()


c#,wpf,multithreading,entity-framework,sqlce
I have the following method running in a non-GUI thread within my application: private async Task PerformContextSubmitAsync() { try { await DataContextProvider.GetDefaultContext().SaveChangesAsync(); } catch (Exception ex) { Log.Error("Error performing context submit", ex); } } Which is called like this: await PerformContextSubmitAsync(); The application is a WPF/Prism based application so I'm...

Run class methods in different threads


java,multithreading,object,methods
Let's suppose I have this class: public class Myclass { method1(); method2(); method3(); } I want to know if there's a way to run all 3 methods in different threads simultaneously. Is there a way to create a class MyThread : public class MyThread{ //implementation } in way that it...

How can I know the lock information in java?


java,multithreading,locking
Is there any tool or way that can get all the information about the locks in java? for example, if there is a java program, it creates two threads, and both threads require locks for some variable. Is there any tools that can output the information like which thread locks...

Java 5 Multi threading, catch thread exceptions


java,multithreading,exception,concurrency,java-5
I've got a class that generates threads (file i/o). I need to catch exceptions in the thread - I don't want to do anything fancy, I want to kill the main thread, rather, stop processing altogether so it can start over. If I catch the exceptions in the thread, that's...

GetWindowsDirectory() API returns wrong (vba\vb6)


vba,winapi,vb6
on my Windows-Terminal user, I'm trying to have two application point to the same Windows directory, one written in VBA one in VB6. When calling the GetWindowsDirectory() API from VB6 it returns the correct path C:\documents and settings\%user%\Windows When calling it from VBA macro, it returns C:\Windows Notice that same...

How to calculate how many times each thread executed a critical section in OpenMP?


c,multithreading,openmp
I have an OpenMP code, where I need to calculate how many times each thread executes the critical section, any idea how to do it? Code samples are highly welcomed.

What happens if all node.js's worker threads are busy


javascript,node.js,multithreading
I try to understand how node.js works and although I have read this article: When is the thread pool used? I am not sure what happens if all worker threads are busy and another async I/O operation is ready to be executed. If I got this http://www.future-processing.pl/blog/on-problems-with-threads-in-node-js/ article right, the...

winapi: from HDC to an HBITMAP


c++,winapi,bitmap,gdi
I would like to do something which I believe is fairly simple but since I am new to the winapi I am finding a lot of problems. Basically I have an HDC (which I am BitBlitting from a loaded Bitmap) and I am drawing a rectangle on it. Then I...

Web API - Set each thread with the HttpRequestMessage id?


c#,.net,multithreading,task-parallel-library,web-api
I have a web api coded in c#. The web api uses functionality which is shared with other in-house components. it depends on single threaded flows and uses thread local storage to store objects, and session information. Please don't say if it's good or bad, that's what I have to...

Set Label From Thread


vb.net,multithreading,winforms
Form1.vb Imports System.Threading Public Class Form1 Dim demoThread As Thread Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim Start As New Class1 Me.demoThread = New Thread( _ New ThreadStart(AddressOf Start.ThreadProcSafe)) Me.demoThread.Start() End Sub Delegate Sub SetTextCallback([text] As String) Public Sub SetText(ByVal [text] As String) ' InvokeRequired required...

performance issues executing list of stored procedures


c#,multithreading,performance,loops
I'm having some performance issues when starting my windows service, the first round my lstSps is long (about 130 stored procedures). Is there anyway to speed this up (except for speeding the stored procedures up)? When the foreach is over and goes over to the second round it goes faster,...

c - Parallelising a function


c,multithreading,table,rainbowtable
I'm trying to implement parallelism to this function I want it to take as many threads as possible, and write the results to a file. The results need to be written in the file in the incrementing order so the first result needs to be written first the second second...

Java how to limit number of threads acting on method


java,multithreading,memory-management
I have java method in my web application doing heavy file operation. The thing is, if more than 5 threads come simultaneously (which will come in testing phase) it breaks down. I mean it cannot handle heavy traffic. That's why I want to handle maximum 5 requests at a time...

Any way to catch an exception occurring on a thread I don't own?


c#,multithreading,exception
I'm using a crappy third party library because unfortunately I have no choice. This library creates a bunch of threads internally when I call it, and occasionally throws a NullReferenceException on one of these threads. Is there any way for me to catch these exceptions even though I don't own...

Can you call dispatch_sync from a concurrent thread to itself without deadlocking?


ios,objective-c,multithreading,swift,grand-central-dispatch
I know you would deadlock by doing this on a serial queue, but I haven't found anything that mentions deadlocking by doing it on a concurrent queue. I just wanted to verify it wont deadlock (it doesn't seem like it would, as it would only block one of the threads...

C# Threading : Threads executed on incorrect object


c#,multithreading
Probably this is a dumb mistake by me, but I can't figure it out. So the scenario is that I retrieve a record from a database every 200ms, if there is one available. On each record, I start a thread. In this case it's a mail that is sent. QMail...

std::condition_variable – notify once but wait thread wakened twice


c++,multithreading
Here's a simple C++ thread pool implementation. It's an altered version orginated from https://github.com/progschj/ThreadPool. #ifndef __THREAD_POOL_H__ #define __THREAD_POOL_H__ #include <vector> #include <queue> #include <memory> #include <thread> #include <chrono> #include <mutex> #include <condition_variable> #include <future> #include <functional> #include <stdexcept> namespace ThreadPool { class FixedThreadPool { public: FixedThreadPool(size_t); template<class F, class......

Is there standard implementation for thread block/resume in java SE?


java,multithreading,wait
I need to block execution of a thread until resumed from another thread. So I wrote my own implementation using wait() method. Which seems to be working, but it is far from simple. Is there any ready to use solution? Preferably in java SE 6? Or do I have to...

MessageBox won't work when handling WM_DESTROY event from DialogBox


c,user-interface,winapi
While elaborating an answer for another question (by myself), I've come up with the idea of using a MessageBox to report the result of my dialog box. It is a WinAPI modal dialog box created with the DialogBox() function. However, I noticed that handling WM_DESTROY in the dialog's procedure function...

Multiple Threads searching on same folder at same time


c#,multithreading,file-search
Currently I have a .txt file of about 170,000 jpg file names and I read them all into a List (fileNames). I want to search ONE folder (this folder has sub-folders) to check if each file in fileNames exists in this folder and if it does, copy it to a...

Pthread id and sleep


c,multithreading,pthreads
I need to do the following: Create a thread that creates 10 threads in a row. Each thread just prints it's ID and sleeps for n seconds, where n is the serial number of current thread. But, I can't get passing arguments right, when I run my code it seems...

How should I read the filename in FILE_NOTIFY_INFORMATION struct


c++,winapi,filesystems,file-monitoring,readdirectorychangesw
I'm trying to monitor file changes but I am not really sure on how to read the filename in the FILE_NOTIFY_INFORMATION struct: HANDLE dwChangeHandles[2]; DWORD dwWaitStatus; wChangeHandles[0] = FindFirstChangeNotification(dirname.c_str(), FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE); if (dwChangeHandles[0] == INVALID_HANDLE_VALUE) printerr(__FILE__,__LINE__,"FindFirstChangeNotification function failed.\n"); ... if ((dwChangeHandles[0] == NULL) || (dwChangeHandles[1] == NULL)) //final validation printerr(__FILE__,__LINE__,"Unexpected...

Does LoadLibrary return NULL or an error code < 32 on failure?


winapi
The MSDN documentation states If the function succeeds, the return value is a handle to the module. If the function fails, the return value is NULL. To get extended error information, call GetLastError. while Microsoft support has a list of return values less than 32 that indicate an error The...

Calling Python code from Twisted


python,multithreading,twisted
First of all, I should say that this might more a design question rather than about code itself. I have a network with one Server and multiple Clients (written in Twisted cause I need these asynchronous non-blocking features), such server-client couple it's just only receiving-sending messages. However, at some point,...

Invoke form showdialog is not modal


vb.net,multithreading,invoke
I have 2 forms, 1 MainForm and 1 Form2. I am trying to display Form2 as a modal form and background from MainForm. Here's what I have so far. The default MainForm appears and after 5 seconds it will show Form2 as a Modal form from a background thread. I...

Show imageview after click wait a moment then hide again [Android]


android,multithreading,imageview,show-hide
I'm trying to show some imageviews after the user has clicked on a button then wait for some time for the user to see which was the correct button to click then hide it again. Something like this: User clicks on button giving his answer -> Score is updated and...

Looking to pause a thread using thread.sleep


java,multithreading
I am using a mouse listener for mouse pressed and released. When the mouse is pressed I want to have a counter incrementing a variable, and when the mouse is released I want to decrement that variable. Right now, my code is working and does that but the increment is...

Node.js and C/C++ integration: how to properly implement callbacks?


c++,node.js,multithreading
I am trying to implement a C++ extension to be integrated with node.js. This extension will internally invoke some blocking calls, so it needs to provide a non-blocking interface to the node.js world. As specified in https://nodejs.org/api/addons.html, there are two ways to implement non-blocking callbacks: a) By using a simple...

How To Get Window handles In Mozilla Firefox


winapi,mfc,ui-automation
How to get handles of all the child windows in Mozilla firefox. Spy++ is showing only one class and window caption for all the windows. I tried using GetWindow and FindWindowEx but got nothing. I want to read URL from mozilla firefox.

Restarting a process from another process


c++,winapi
I have two processes: ProcessA and ProcessB. When i launch my application, i call ProcessA which uses CreateProcess() to launch ProcessB. ProcessA is killed by ProcessB when my application receives command A. Likewise, ProcessB should relaunch ProcessA when it receives command B. Where i am stuck on is on the...

EXC_BAD_ACCESS error occurring when running recursive merge sort method in a thread


c++,multithreading,sorting,recursion
I'm having trouble with my C++ code in xCode. I've tried debugging and I can't fix it. I know it's roughly when my mergeSort() method calls my mergeNumbers() method. I know it's not the method itself because I've run the method without threading and it works just fine. It's when...

Images not appearing on WPF form when loading asynchronously


c#,wpf,multithreading,listbox,backgroundworker
I'm attempting to display (in a ListBox with a custom DataTemplate) a series of BitmapSource frames (thumbnails) extracted from a multi-page tiff image. When I process the tiff on the UI thread, and either directly add the images to a listbox's item collection or add them to a bound ObservableCollection,...

Multi-Threading error when binding a StringProperty


java,multithreading,javafx,javafx-8
I have a question about multi-threading and the binding of a StringProperty. I have a class CacheManager, which contains a Thread which updates my cache with the changes on the server. Now, I want to notify the user with a text and percentage of the progress (which are a Label...

how to change Text to Speech voice and how to insert characters into char array


c++,arrays,windows,winapi,text-to-speech
I need to change the voie of the Text To Speech engine. when a menu is selected ID_SPEAK_PLAY I get the text of an edit box and simply read it. my situation can be solved in two ways : insert the XML code at the begining of ptrData without using...

Interleaving processes on two threads


c#,multithreading,synchronization
I have a library that I can use to access some tabular data. This library is the only way I have of accessing the data. The method I am using takes a query string and a callback that is called for each result row. Currently, the callback loads each row...

wait for an event regulary


multithreading,events
In a program I need to wait for an event (keypress) and get it's char. after that program will continue. this progress will Repeat several time. in my first try, codes run and any character did not save. I find out I should use threading but I am not Familiar...

Crystal convert the idea behind Thread pool to Fibers/spawn


multithreading,coroutine,crystal-lang
I'm having some hard time learning the idea behind Fibers\coroutines and the implementation in Crystal. I hope this is the right place to ask this, I'll totally accept a "not here" answer :) This is my usual way of handling multi-threading in Ruby: threads = [] max_threads = 10 loop...

hashmap iterator when used inside synchronized method


java,multithreading,hashmap
so let's say I have a Hashmap that looks like: key : value (string 1, queue 1) (string 2, queue 2) (string 3, queue 3) I also have a synchronized method that will access this hashmap, and an iterator is created inside the method: Iterator it = hashmap.iterator(); while(it.hasNext()){ Queue...

Atomic/not-atomic mix, any guarantees?


c++,multithreading,c++11,atomic
Let's I have GUI thread with code like this: std::vector<int> vec; std::atomic<bool> data_ready{false}; std::thread th([&data_ready, &vec]() { //we get data vec.push_back(something); data_ready = true; }); draw_progress_dialog(); while (!data_ready) { process_not_user_events(); sleep_a_little(); } //is it here safe to use vec? As you see I not protect "vec" by any kind of...

If statement not working in vb6


winapi,vb6
I want to make a program which could close a window with the title "Personalization" in vb6. The problem is that the if statement is not working.Here's my code(it only finds a window named "Personalization" without closing it): Option Explicit Private Sub Command1_Click() Timer1.Enabled = Not Timer1.Enabled End Sub Private...

java multithreading start() and run() [duplicate]


java,multithreading
This question already has an answer here: Java: What's the difference between Thread start() and Runnable run() 10 answers Below is my Multithreading class: public class Multithreading extends Thread{ public void run(){ for(int i=1;i<5;i++){ try{ Thread.sleep(500); }catch(InterruptedException e){ System.out.println(e); } System.out.println(i); } } public static void main(String args[]) {...

Does wait() need synchronization on local variable


java,multithreading,synchronization
I had this code (which was working fine): public static void runOnUiThread(Activity c, final Runnable action) { // Check if we are on the UI Thread if (Looper.getMainLooper() == Looper.myLooper()) { // If we are, execute immediately action.run(); return; } // Else run the runnable on the UI Thread and...

Why does this code catch block not execute?


c++,multithreading,error-handling,try-catch
The catch handler is not run. But why? If the thread t is started before the try block, the catch handler runs. If the catch block's type does not match the type thrown, the program exits explaining that the thread terminated with an uncaught exception, suggesting that the exception is...

More convenient way to work with strings in winapi calls


string,winapi,rust
I'm looking for more convenient way to work with std::String in winapi calls in Rust. Using rust v 0.12.0-nigtly with winapi 0.1.22 and user32-sys 0.1.1 Now I'm using something like this: use winapi; use user32; pub fn get_window_title(handle: i32) -> String { let mut v: Vec<u16> = Vec::new(); v.reserve(255); let...

Calling dispatch_sync from a concurrent queue - does it block entirely?


ios,objective-c,multithreading,swift,grand-central-dispatch
Let's say I hypothetically call a dispatch_sync from a concurrent queue - does it block the entire queue or just that thread of execution?

Simple thread/mutex test application is crashing


c++,multithreading,c++11,mutex,mingw-w64
I wrote a simple test program which accumulates random samples to a buffer using multiple threads. Each thread uses a stack for reducing the mutex waits. This is for investigating problems in a much larger program. The code currently crashes on mingw-w64 4.9.2 Any idea why? Debugging halts on "signal-received"...