w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Block of sub-thread makes main thread blocking if sub-thread hosts a IE control
You cannot just create COM objects (and UI) on another thread and pass them to main thread. Why don't create you create it on a main thread like other people do? I think it is quite impossible to pass UI to another thread (message loops of main window and child controls are hosted on different threads, and child/parent notifications just won't work). And as for COM, you need both initialize both threads for COM and marshal pointer between them: http://msdn.microsoft.com/en-us/library/ms678428(v=vs.85).aspx

Categories : C++

Visual Basic, Child Thread Blocking Main Thread
From what i can tell all calls to the System are also GUI Thread based no matter if you want them or not. And Control.CheckForIllegalCrossThreadCalls = False is very bad, you always want to write your thread and ( if beginner ) run code and everytime it breaks out to code to write a delegate and an invoke function for that part of your thread ( taking up the most minimal time ) one can in the Gui(Main) thread. Here is an example with full sourcecode http://www.codeproject.com/Articles/15104/Multithreading-with-VB-NET-A-beginner-s-choice in your thread Control.CheckForIllegalCrossThreadCalls = False -- this needs removed If check_scanfirst.Checked Then -- this needs a delegate and invoke method status1.Text = "Scanning..." -- this needs a delegat

Categories : Vb.Net

How to determine what's blocking the main thread
You may be blocking the main thread or you might be flooding it with events. I would suggest three things: Grab a timestamp for when the timecode arrives in the CoreMIDI callback thread (see mach_absolute_time(). Then grab the current time when your main thread work is being done. You can then adjust accordingly based on how much time has elapsed between posting to the main thread and it actually being processed. create some kind of coalescing mechanism such that when your main thread is blocked, interim timecode events (that are now out of date) are tossed. This can be as simple as a global NSUInteger that is incremented every time an event is received. The block dispatched to the main queue could capture the current value on creation, then check it when it is processed. If it

Categories : Objective C

Run bash script in thread not blocking the main loop
If you use subprocess.Popen you wait for the returned handler with .wait(). You can investigate if the process has completed [and the exit code] with .poll() or interact with it (standard in/out) with .communicate(). The documentation is found here: http://docs.python.org/2/library/subprocess.html#module-subprocess what have you tried?

Categories : Python

Performing many UIKit operations blocking main thread
UIViews are not thread safe in normal usage, and all interaction should occur on the main thread. That said, you should be able to, on some background thread (dispatch queue), create the view, modify its parameters, set complex background colors, etc - as long as the view is not connected to anything (and thus receiving events from iOS). Once the view is completely setup and wired, then dispatch a block with it to the main queue and only then add it as a subview to some other view. What I would do is dispatch all this work to the normal priority queue after having set up my initial video clip. When all the views have been posted back to the main queue (and thus this work is complete), you can stop the video and start interacting with the user.

Categories : IOS

Is an open web socket connection blocking ajax request?
The call should be asynchronous, but perhaps the connect is failing. Try adding an onerror handler for the websocket and see what happens. ws.onerror = function(){ console.log(evt.data); } Also, if you could make a JSFiddle or include the HTML it might be that the button event handler is wrong and it isn't related to the websocket code at all.

Categories : Javascript

Will an ajax request ever reach readyState 4 if a local firewall is blocking the URL requested?
Yes it will. For example, look at this code. function readyStateCallback () { jsprint(this.readyState); }; var oReq = new XMLHttpRequest(); oReq.onreadystatechange = readyStateCallback; oReq.open("get", "http://foobarbaz.nnn", true); oReq.send(); You can try it on this fiddle. Every request triggers a ready state of 1 and 4, but not necessarily ready states 2 or 3. See the XMLHttpRequest MDN docs. 0 UNSENT open() has not been called yet. 1 OPENED send() has not been called yet. 2 HEADERS_RECEIVED send() has been called, and headers and status are available. 3 LOADING Downloading; responseText holds partial data. 4 DONE The operation is complete. To determine if the request failed (such as being blocked

Categories : Javascript

I want to put my computational stuff in secondary thread while keeping main loop in main thread
You cannot call OpenGL functions from multiple threads generally speaking (without using multiple render contexts, or context switching). You have to have a bound render context to issue OpenGL commands, and window systems will restrict you to a single context-per thread. To get around this, you are going to need to use a framework that is more advanced than GLUT. The basic idea is that you need to share resources between contexts, one for uploading data into and one for actually rendering. But the more I think about this, there is no real reason for you to do any of this. Stick to using a single thread for all GL commands, maybe load image files from disk in another thread. And signal the thread that you do your rendering in to send the data to GL using glTexImage2D (...). Your use-case

Categories : C++

Open a modal form from a background thread to block UI thread without also blocking background thread
You are calling the address from within the sub it is created in. The Address needs to be called from outside this sub. Private Sub StartBlockingTask(ByVal reason As String) If Me.InvokeRequired Then Dim del As New BlockingDelegate(AddressOf StartBlockingTask) Private Sub EndBlockingTask() If Me.InvokeRequired Then Dim del As New BlockingDelegate(AddressOf EndBlockingTask) You need to create two delegates. One for StartBlockingTask and one for EndBlockingTask This is an example from MSDN, Delegate Sub MySubDelegate(ByVal x As Integer) Protected Sub Test() Dim c2 As New class2() ' Test the delegate. c2.DelegateTest() End Sub Class class1 Sub Sub1(ByVal x As Integer) MessageBox.Show("The value of x is: " & CStr(x)) End Sub

Categories : Vb.Net

Is it safe to access a variable from the main thread after it was written to by another thread and after that thread was joined?
Yes, that particular code snippet is thread safe; barriers or locks are not required. This is the timeline of events with respect to your code: thread 1 -------- | int x = 0; (write 0 to x) | std::thread thread 2 (start thread 2) --------> -------- | | join(); x = 1; (thread 1 suspended) (write 1 to x) . | . thread 2 returns . | (thread 1 resumes) <------- x | std::cout << x; (read from x) | thread 1 returns | x As you can see, at no point is x being accessed by more than one thread. In fact, the use of join() effectively makes all accesses to x happen in sequential order,

Categories : C++

How can i resolve the Exception in thread "main" java.lang.NoSuchMethodError: main
Your main method is not static, and you should make it static. Check this to see why public static void main(String [] args)

Categories : Java

Two instances of same class running via main - what is their associated unique identifier of each thread of main?
Your current approach of generating a unique id yourself is the best idea. The Java and JVM specifications do not define a natural unique identifier. This means that any inherently pre-existing id will be specific to either the operating system or the JVM implementation. This will tie your code to a specific platform and make it less portable. Whether or not UUID.randomUUID() is the best way to generate an id yourself depends on your usecase. One alternative would be to use a shared temp file with a counter to keep track of all the currently running processes.

Categories : Java

Is it possible to check that main thread is idle / to drain a main run loop?
you can try this while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true) == kCFRunLoopRunHandledSource); this will run until no more things in the run loop. you can try to change the time interval to 0.1 if 0 is not working.

Categories : IOS

Why dispatch_sync( ) call on main queue is blocking the main queue?
When using dispatch_sync on a serial queue (like the main queue) the current thread has to wait until the dispatched code is executed. A dead lock occurs when a block is dispatched synchronously on from a serial queue to the same queue.

Categories : Iphone

What is the relation between the main() method and main thread in Java?
Is there any relation between main() method and Main Thread ? When the JVM starts, it creates a thread called "Main". Your program will run on this thread, unless you create additional threads yourself. The first thing the "Main" thread does is to look for your static void main(String[] argv) method and invoke it. That is the entry-point to your program. If you want things to happen "at the same time", you can create multiple threads, and give each something to execute. They will then continue to do these things concurrently. The JVM also creates some internal threads for background work such as garbage collection.

Categories : Java

How to manage worker thread lifecycles when main Java thread terminates?
If SIGKILL is a unix "kill -9" there's nothing you can do about it. For graceful exits, use a try/catch/finally in your main. The catch will catch your exceptions and allow you to do what needs to be done (recover? abort?) The finally will give you the hook to spin down your threads gracefully. Reviewing your code quickly, I don't see where you're keeping track of your thread instances. You'll need those if you're going to tell them to spin down. psuedocode: static Main(...) { ArrayList threads = new ArrayList(); try { for (each thread you want to spin up) { threads.add(a new Thread()) } } catch { assuming all are fatal. } finally { for(each thread t in threads) { t.shutdown(); t.join(); /* Be p

Categories : Java

Keeping main thread (Qt Application) responsive while some other thread is processing (POSIX)
There are several options available to you. It looks like you're using a thread, but then calling sleep in the main thread, which is basically the same as not using thread to do your work at all! You need to leverage Qt processes as illustrated below: You can use a QProcess in which you start() and use the signal finished() to notify the main thread that it is complete. This is probably what you want to use. All you have to do is: QProcess *proc = new QProcess; proc->start("theProcess", QStringList() << "the" << "arguments"); connect(proc, SIGNAL(finished()), this, SLOT(someSlotToUse())); This sequence of code will start a new process with your arguments, and then call someSlotToUse() when the process is complete. You can use a QThread along the same pattern. Basicall

Categories : Linux

does this strategy that use core data with multiple thread will block main thread ?
You usually configure batching on a fetch request for NSFetchedResultsController. Then when you perform fetch in NSFetchedResultsController, and it in turn executes the fetch request, that request is very minimal, because it basically fetches only object IDs and no data. Later, when some object from the results is accessed (typically in -tableView:cellForRowAtIndexPath:), first batch is being fetched. This fetch also takes little time (if you configure small enough batch size). When you scroll and access the first object that is not in a batch, the next batch is fetched and so on. This way no big fetches are performed on the main thread. There is one problem with this approach and the pattern you've chosen. For some reason batching doesn't work when fetch request is executed in a child co

Categories : IOS

Suspending worker-thread and wait for user interaction on main-thread
If you change the "wakeup" mechanism the concept is not bad. Instead of a bool? and periodically waking up the worker on its own it would be better to use a bool and a ManualResetEvent. The worker notifies the UI and waits on the event (immediately blocking). The UI interacts with the user, sets the bool appropriately and signals the event (releasing the worker, which inspects the bool value and acts accordingly). Of course the above can be implemented in a variety of manners, and the implementation leaves quite a bit of room for engineering. On one end of the scale you could have tightly coupled code with a raw flag and event, while on the other you could have an abstract "feedback service" that the worker queries. This would enable you to swap one implementation of the feedback servic

Categories : C#

cocoa downloading file callbacks not called when downloaded from background thread, works on main thread
I think you should start the run loop to which your NSURLDownload object is attached. By default it will use the current thread's run loop, so you probably should do something like this after initialization of NSURLDownload object: NSRunLoop* runLoop = [NSRunLoop currentRunLoop]; while (!self.downloaded && !self.error && [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) ; Properties self.downloaded and self.error should be set in your callbacks. In main thread run loop probably started by the NSApplication object.

Categories : Osx

How to send a bitmap data to the main thread from a backgrund thread?
Either define a BroadcastReceiver and send an Intent from your worker thread, since Bitmap is Parcelable. You can also use startIntent if you want to launch a new activity to handle the bitmap, thus you won't need to define a BroadcastReceiver. Or define an Handler in your main thread, pass it to your worker thread and then post a Runnable to be executed on the main thread. You can also use runOnUiThread().

Categories : Android

Newly created thread not firing until main thread finished
You have to create multiple threads if you want them to run the way you are thinking (simultaneously).Take a look at this link and try creating more than one thread. This should help your problems. Cheers http://msdn.microsoft.com/en-us/library/ck8bc5c6%28v=vs.80%29.aspx

Categories : Vb.Net

QThread: Call child thread method from main thread
to run some function in a separate thread you can use QtConcurrent::run (i use it with QFutureWatcher). To run it every 5 or so seconds, use QElapsedTimer class QFuture<void> future = QtConcurrent::run(this, &MyClass::foo2, ...foo2 arguments); http://qt-project.org/doc/qt-4.8/qtconcurrentrun.html#run or check it here http://stackoverflow.com/search?q=QtConcurrent%3A%3Arun or you can subclass QThread, reimplement QThread::run() method with the stuff you want to happen in your thread, and then create an instance of your thread and call start() on it.

Categories : Multithreading

How to notify outside thread of main thread state without using global variables?
You can still pass arguments to your worker thread at construction time. But do not pass it copies of your state variables (because as you said, they "only captures the state of the main thread at a certain point in time", which is the worker thread creation time). Instead, pass it pointers (or references) to your state variables. Because they are pointers, your worker thread will have access to the latest data from the main thread without the need to use globals. Below is a pseudo-code example (without any synchronization mechanism, like mutex): DWORD MyThreadFunction( LPVOID argument ); int main() { bool mySyncVar = false; bool* mySyncVarPtr = &mySyncVar; CreateThread( NULL, // default security attributes 0, // use def

Categories : C++

Why main thread is slower than worker thread in pthread-win32?
What could be happening is that the worker thread execution is being interleaved with main's execution, so that some of the worker thread's execution time is being counted against main's time. You could try putting a sleep(10) (some time larger than the run-time of the worker and of main) at the very beginning of the worker and run again.

Categories : C++

Thread Blocking the UI
When you are trying to get result of task task.Result main thread will be blocked until task will finish it's execution (i.e. result will be available). Use task.ContinueWith if you don't want to wait for async operation completion: Task<int> task = tcs.Task; task.ContinueWith(t => { MessageBox.Show(t.Result.ToString()); }); BTW there is nice feature in .NET 4.5 for resuming suspended operation when task is completed - async methods: private async void Form1_Load(object sender, EventArgs e) { var tcs = new TaskCompletionSource<int>(); new Thread(() => { Thread.Sleep(2000); tcs.SetResult(42); }).Start(); int result = await tcs.Task; MessageBox.Show(result.ToString()); } This method will yield control to caller immediately after startin

Categories : C#

cordova 3.0 FileWriter THREAD WARNING: exec() call to File.write blocked the main thread...should use CordovaInterface.getThreadPool()
Yes, these messages are important and you should use background thread for complicated tasks, such as file writing. The reason of this problem is that these tasks are blocking cordova and you could experience for example UI lags. If your next actions are dependent on this task being completed, I recommend you using callback method.

Categories : Android

can we change a background thread operation to main thread?
The part in that method you want to run on the main thread, just stick it inside this GCD block and it will run it on the main thread: dispatch_sync(dispatch_get_main_queue(), ^{ //put stuff here });

Categories : IOS

Main thread closed while the worker thread not finished
You should terminate the workthread safely before the maindlg is destroyed. Here is the answer [Terminating a thread gracefully not using TerminateThread() ]

Categories : C++

how to prevent main thread ios from killing background thread
Brad Larson had some suggestions on this post that should help you. In your appDelegate, when your app is getting pushed to the background, it calls applicationDidEnterBackground. From this routine, you can see if your method is currently in progress, and can behave accordingly. Depending on how long your task takes to run there are two options: If it will take significantly less than 5 seconds, you can just have your applicationDidEnterBackground wait until your task is completed before releasing. If you take longer than 5 seconds, your app will just get force-killed. If it could be a while, you can try beginBackgroundTaskWithExpirationHandler: to start a background task that finishes off your task.

Categories : IOS

How to update a DataTable created on Main Thread by a new thread in C#?
You can try inserting images before you pass it as Datasource to uxImageGrid. Add image column to DTImageLis. DTImageList.Columns.Add("Image", typeof(System.Drawing.Image)); Add the image to datatable based on Name,Id etc and bind it to uxImageGrid uxImageGrid.Datasource=DTImageList;

Categories : C#

THREAD blocking issue?
It's hard to follow your architecture here, but in general Java web apps should not be spawning threads or working directly with multi-threaded stand-alone apps. I would recommend refactoring the web app so that all of the credit card processing is done within the Java servlets instead of having them go back and forth to a stand-alone app.

Categories : Java

Non blocking thread synchronization
you dont need lock free synchronization. Just fire up the threads and have them signal objects when complete. Do a non-blocking call on the sync handle if you dont want to block the UI thread ie WaitForMultipleObjects(n,lpHandles, 0, 0); the last 0 says return rather than wait if object(s) not signalled

Categories : C++

Thread blocking UI in android
In stead of creating the connection manager from the UI Thread, why dont you create it in a worker thread as follows: protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_main); super.onCreate(savedInstanceState); new Thread(new Runnable() { @Override public void run() { connectionManager= new ConnectionManager(YourActivity.this); connectionManager.start(); } }).start(); This way you never get to block the UI Thread, hope this helps... Regards!

Categories : Android

Run multiple thread at a same time then run main thread
You can call join() on the threads. Assuming that your threads are in myThreads and you don't want your thread to be interruptible // ... // create threads and start them // ... for (Thread t : myThreads) { while (t.isAlive()) { try { t.join(); } catch (InterruptedException e) { } } } If it should be interruptible: // ... // create threads and start them // ... for (Thread t : myThreads) t.join();

Categories : Java

InputStream reader blocking thread
The read indeed blocks the thread running if no data is available. What you want is to read a byte with a timeout ? Look for answer to this in Is it possible to read from a InputStream with a timeout?

Categories : Java

Why is this async method blocking the UI thread?
It looks like the UI is responsive during the Task.Delay but is blocked otherwise... Well yes. That's exactly what's happening. Task.Delay is the only chance you're giving the UI thread to work. Your asynchronous method is executing on the UI thread - as soon as the "delaying" task completes, you'll end up with a continuation waiting to execute on the UI thread which will redraw and then delay again. Fundamentally, if your Redraw method is too slow to be called ~60 times per second, you need a different approach. It's very important to understand that async doesn't put the method onto a different thread - it just allows you to act asynchronously. (Your description and title suggest that you expected your method not to be using the UI thread for any significant time.) Additionally,

Categories : C#

Java logging thread blocking
You have a classic deadlock situation. Thread catalina-exec-49 holds 3 locks (on a org.apache.tomcat.util.net.NioChannel, a com.sun.xml.ws.api.pipe.Fiber and a it.codegen.tbx.ResourceManager) and it's waiting to acquire a 4th (to enter the synchronized publish method on a it.codegen.logging.CGFileHandler. The problem is that another thread has already acquired the lock on the CGFileHandler (maybe by entering the publish method, or another synchronized method on the same instance), and is waiting to acquire one of the locks that catalina-exec-49 holds. Neither thread can advance, leading to deadlock. Without seeing detailed code and stack dumps, etc., I can't give you specific advice, but generally you should: limit the extent of synchronized blocks to the bare minimum avoid calling out

Categories : Java

Exiting a thread that contains a blocking statement in c
Make sure to mask off SIGINT on all your child threads, as signal delivery is to a single, arbitrary thread without the signal masked. This guarantees your "management thread" will get the ctrl-c. Then, use pthread_kill from your management thread to send signals to your other threads using an unmasked signal. This will interrupt your blocking calls and allow you to test flags and such. Read this: http://man7.org/linux/man-pages/man7/signal.7.html especially the section titled: Signal mask and pending signals Use pthread_sigmask to examine and change your thread's signal mask.

Categories : C

How can I timeout a task without it blocking the UI thread?
Older solution, not feasible for tasks that are not cancellation-aware You should pass a CancellationToken: private async Task DownloadFile() { WebClient client = new WebClient(); using(var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60)) { var downloadTask = Task.Run( () => client.DownloadFile("http://www.worldofcats.com/bigkitty.zip", "c:\cats\"), cts.Token ); await downloadTask; } } Now when you await DownloadFile() you can wrap it in a try/catch block to catch the TaskCanceledException (or OperationCanceledException): try { await DownloadFile(); } catch(TaskCanceledException) { //Timeout! } [EDIT] As was noticed i

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.