w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Cross-thread operation not valid, control accessed from thread other than the thread it was created on
From MSDN documentation - InvokeRequired can return false if Invoke is not required (the call occurs on the same thread), or if the control was created on a different thread but the control's handle has not yet been created. In the case where the control's handle has not yet been created, you should not simply call properties, methods, or events on the control. This might cause the control's handle to be created on the background thread, isolating the control on a thread without a message pump and making the application unstable. You can protect against this case by also checking the value of IsHandleCreated when InvokeRequired returns false on a background thread. If the control handle has not yet been created, you must wait until it has been created befor

Categories : C#

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++

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++

What does Thread refer to, in method calls to Thread.currentThread(); and Thread.sleep();?
Thread is the name of a class. currentThread() and sleep() are static methods of this class, that's why you're able to reference them without creating objects of the class. You can write currentThread() instead of Thread.currentThread() only if you've performed static import of the Thread class itself.

Categories : Java

Cross-thread operation accessed from a thread other than the thread it was created on
Use the BackgroundWorker control, you can read the tutorial on the topic on MSDN Basically, on the button's click event you execute: if(!bw.IsBusy) bw.RunWorkerAsync(); This will run any code you put into backgroundworker's DoWork event on a background thread. After your code finishes, it will execute RunWorkerCompleted event that will run on the main thread, and that's where you can proceed to update stuff that you couldn't before due to cross-threading. Note that you can pass parameters to the DoWork event and results from DoWork to RunWorkerCompleted event.

Categories : C#

How to let a thread A wait until thread B is finished, then continue thread A?
The thing you are looking for is called a Semaphore. Here's a link to your question with that term plugged in: Objective-C Sempaphore Discussion Btw, the word "semaphore" means traffic light.

Categories : IOS

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

MFC: sending a msg from worker thread to the Main thread to stop the worker thread
Actually, the only safe way to do anything to a worker thread is from within the worker thread itself. It should probably be structured as a while(bRun) loop so it runs until the program is shutting down. Whatever you are trying to do (stop and start) should be handled by code in the while loop.

Categories : C++

Sharing data between master thread and slave thread in interrupt driven environment in C
Assuming that f2() uses the same mutex in the shared structure to lock before reading the data that the thread th uses to modify the data, I don't see any issues. If you have more than one thread calling f2(), you may want to use a read-write lock for reading and writing of the thread status of th. The mutex could still be used to serialize the thread creation check. You could also use a pthread_rwlock_wrlock() to serialize th creation, but the code is arguably less clear. Using a mutex to serialize th creation in f2(): pthread_rwlock_rdlock(&shared.rwlock); result = shared.th_status; if (! shared.th_created) { pthread_mutex_lock(&shared.mutex); if (! shared.th_created) { pthread_create(...); shrared.th_created = 1; } pthread_mutex_unlock(&sha

Categories : C

Error: The calling thread cannot access this object because a different thread owns it - Kinect
Ok so basically you're trying to update the UI from a thread that is not the main thread, and this never works without an invoke of some description. Have a look at the answers on this thread, it looks to be exactly the same problem as you're having The calling thread cannot access this object because a different thread owns it.How do i edit the image? According to those answers you should change the code in videoDisplay() to read as follows: ... Action action = delegate { kinectVideo.Source = colorImageBitmap; }; kinectVideo.Dispatcher.Invoke(action); if (colorImageBitmap == null){ ... And if that doesn't work try: ... colorImageBitmap.Freeze(); Action action = delegate { kinectVideo.Source = colorImageBitmap; }; kinectVideo.Dispatcher.Invoke(action); if (colorImageBitma

Categories : Multithreading

Creating a new thread with parameters - Thread is created but it doesn't show the data
Swing is a single threaded environment, all updates and interactions to the UI are expected to be executed from within the context of the Event Dispatching Thread. This also means that any action which blocks the EDT will stop the UI from begin updated/repainted or process any new events that might have occurred. See Concurrency in Swing for more details. Instead of using a Thread and Runnable, you should probably use a SwingWorker. It provides a means by which processing can be done in a background thread, but also provides simple to use methods to allow you to process the results within the EDT. For example... public class StationListWorker extends SwingWorker<Void, Object[]> { // The data to be processed... private List<Station> stations; // The model the r

Categories : Java

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#

Multiple threads writing, one thread reading from queue, thread safety
ConcurrentQueue is a good start and probably all you need to know to make it work. Watch out for other resources that might be shared between your threads that will need locking or using specialized concurrent classes.

Categories : Dotnet

using zmq PUSH socket per producer thread vs dedicated zmq thread for all threaded producers
A lot depends on how many producers there are. If there are only a handful, then having one socket per thread is manageable, and works well. If there are many, then a producer-consumer queue with a single socket pushing (effectively being a consumer of the queue and singe producer for downstream sockets) is probably going to be faster. Having lots of sockets running is not without cost. The main pro of the first case is that it is much more easily scaled out to separate processes for each producer, each one single-threaded with its own socket.

Categories : Multithreading

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

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

JMS: Is it OK to read via MessageConsumer.receive() on one thread, then call Session.commit() from another thread?
Maybe you have found a way in the specification. A quote from the doc of Sessionhttp://docs.oracle.com/javaee/1.3/api/javax/jms/Session.html A Session object is a single-threaded context for producing and consuming messages. Although it may allocate provider resources outside the Java virtual machine (JVM), it is considered a lightweight JMS object. So it's single-threaded; and it's not expensive to create one. And you have to pay attention to The close method is the only session method that can be called while some other session method is being executed in another thread. So you have to make sure that read and commit do not overlap, for example. From a technical point of view I would refactor it; the code will be easier to read/maintain. Resource handling (open/close) woul

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

Java, using wait and notify properly to pause thread execution from another thread
you'd better use SwingUtilities.invokeLater in order to update UI instead of using your worker thread if you need to 'cancel' your thread, you need to make your "running" flag as volatile instead of using "synchronized", I'd suggest to use ReentrantLock and it's conditions

Categories : Java

Boost Thread Check Whether Current Thread's Is Equal To Another Native Handle
Yes this is possible. although I think you are misunderstanding here : Now I want to check if the currently running process is the same as the one assigned to bob Compare the thread id. with the native handle on windows:GetThreadId On mac and posix I think you have a pthread_t * as handle. This type is the id of the thread. You can compare it with pthraed_equal i think see here So you answer is compare the native id type with platform dependant code. If fact the main issue is that the native id types are not the same on the 2 platforms.

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

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 can I write a loop which understand a thread has finished and starts new thread?
The thread class has these methods, which could be used to do what you want: Thread.join() Thread.isAlive() But, you probably really want to use a thread pool, like this: ExecutorService executor = Executors.newFixedThreadPool(5); for(int i=0;i<N;i++) { executor.submit(new Runnable() { @Override public void run() { } }); }

Categories : Java

Can a background thread trigger a message handler on UI thread in android
Not sure if I understood your problem completely, but I believe there are two ways to achieve what you want: 1- Start an AsyncTask instead of a thread. AsyncTask's onPostExecute() will run in the UI thread, which means you can do anything UI-related in there. You can start the AsyncTask in onCreate(), and, once it finished, it calls a method on your activity which does: myAdapter.notifyDataSetChanged(); 2- Use runOnUIThread()

Categories : Android

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 long a thread wait while other thread accessing synchronized block?
If the variable lock has been synchronized on in one thread, all other threads attempting to use lock to synchronize will be blocked until lock is no longer being synchronized on. //all other threads waiting on thread 1... synchronized(lock) { //thread 1 storing digits of pi into linked list... or whatevs. } As others have said, threads will wait indefinitely for a variable to become free for synchronization.

Categories : Java

The calling thread cannot access this object because a different thread owns it. Even after using dispatcher
When using WPF, we work with data objects that are displayed by relating UI objects. Using Bindings, we update the UI by manipulating the data objects. I would implement something like this for your situation... first create a DependencyProperty in your MainWindow.cs to bind to: public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register( "Items", typeof(ObservableCollection<Image>), typeof(MainWindow), new UIPropertyMetadata(new ObservableCollection<Image>())); public ObservableCollection<Image> Items { get { return (ObservableCollection<Image>)GetValue(ItemsProperty); } set { SetValue(ItemsProperty, value); } } Then add the UI code that will display the data property: <ItemsControl ItemsSource="{Binding Items}">

Categories : C#

log4j in a multithread environment. One Appender per Thread or one Logger per Thread or...?
From an Apache log4j FAQ: Yes, log4j is thread-safe. Log4j components are designed to be used in heavily multithreaded systems. As Marko Topolnik comments, just ignore multithreading when planning your logging statements, and let log4j take care of it.

Categories : Java

Java thread updating jProgressBar does not update when thread is called again
I'm guessing that your problem is likely because percentComplete is maximum the second time you press your button. Suggestions: reset percentComplete each time the code is run. Avoid making Swing calls from within a background thread, including reading textfield text. Rather do this in the SwingWorker's constructor, not in its doInBackground(...) method. You appear to be making static field and/or method calls. If so, don't as this will bite you in the end, and instead create and pass valid references. I'm guessing that to do this, you will want to create a new BulkProcessor object. Calling run() and then update() as you're doing, getting two threads to run concurrently looks dangerous to me, a possible set up for a race condition. Edit You should look into using a SwingWorker's

Categories : Java

what's the difference between thread sheduling actor and thread context switch
Firstly I don't think the my question is duplication of the reffered link. Secondly I don't think the referred question is properly answered. but they provide some related infomation that shed lights on my question. Important Actors that Unify Threads and Events - Philipp Haller, Martin Odersky Actors are not that light weight at all, which can be concluded from the benchmarks in the reference paper. for thread based actors , actor per thread, so essentially the same for event based actors , when actors react, the state of it will be persisted out to thread queue, a new actor state will switched in, so in a sense there are data switches happening within the worker thread, but there are no kernel calls happened which I think is the most proeminent difference compared with actor data swit

Categories : Dotnet

This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread
If I'm not mistaken, in WPF 4.5, you should be able to do this without any problem. Now to solve this, you should use the synchronization context. Before you launch the thread, you have to store the synchronization context in the ui thread. var uiContext = SynchronizationContext.Current; Then you use it in your thread: uiContext.Send(x => _matchObsCollection.Add(match), null); Take a look at this tuto http://www.codeproject.com/Articles/31971/Understanding-SynchronizationContext-Part-I

Categories : Wpf

Is the Python non-daemon thread a non-detached thread? When is its resource freed?
If you spawn a thread that runs a function, and then that function completes before the end of the program, then yes, the thread will get garbage collected once it is (a) no longer running, and (b) no longer referenced by anything else.

Categories : Python

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

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

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++

Why use Thread.currentThread().isInterrupted() instead of Thread.interrupted() when implementing Runnable?
The difference is very subtle and usually doesn't matter. You can obviously set or clear the interrupted flag as you wish. There isn't even a standard practice that says "use one and never use the other". The main point is to know what you are doing with the interrupted flag: leaving it in a state which you didn't specifically intend would definitely not make just a subtle difference. Never use Thread.currentThread().interrupted(). This would just be misleading, especially if you had someOtherThread.interrupted().

Categories : Java

Killing child thread in Perl cause death of the parent thread
As the message says, it's a static method call threads->exit(1); # ok Not an instance method call $th1->exit(1); # not ok unless $th1 contains the string "threads"

Categories : Multithreading

displaying Busy Indicator while user authentication on a thread : Threading error (The calling thread cannot access this object)
Please try this: private BackgroundWorker _BgWorker; public LoginFormViewModel() { _BgWorker = new BackgroundWorker(); _BgWorker.DoWork += new DoWorkEventHandler(bgw_DoWork); _BgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted); _BgWorker.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged); _BgWorker.RunWorkerAsync(); } void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // write your code to check authentication } void bgw_DoWork(object sender, DoWorkEventArgs e) { // write you code to open window } void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e) { // write the code for busy indicator like ShowProgress= true; } Hope this may help you.

Categories : C#

displaying Busy Indicator on a thread and launching the application : Threading error (The calling thread cannot access this object)
the exception is thrown because you cannot access UI element form a background thread. you have to either call the objMainWindow.Show() from main/UI thread or ask the dispatcher to call it for you if you have to call it from the backgorund thread you can do it like this: Action act = () => { MainWindow objMainWindow = new MainWindow(); objMainWindow.Show(); Application.Current.MainWindow.Close(); }; System.Windows.Application.Current.Dispatcher.Invoke(act); I would recomend reading the following MSDN Article

Categories : C#



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