Thread synchronization and setting thread's priority |
You can not achieve it by using just priority, because if any of worker
thread is holding a lock then priority can not force them to free it. Here
is one implementation I can think off..
As soon as the sender thread will wake up after 1 sec duration it will send
a signal to the worker process. And in the signal handler free the lock
that is held by the workers(I guess a binary semaphore would be good here,
so put it's value to 0 in the signal handler), so whatever worker thread
will try to access it will get blocked. At sender side send all the packets
and at the end again set semaphore back to 1.
This is one implementation, you can think think your own like that but
eventually it should work .:)
|
Is setting a hashmap thread safe? |
First off, Java's HashMap class is not thread safe, so there are no
guarantees when reads and writes are happening concurrently.
However, since reads and writes to references in Java are atomic, then the
pattern you described could be thread-safe as long as the refresh code is
not mutating the old map. For example, the following would be fine:
// this refresh code would be thread-safe
Map<String, String> copy = new HashMap<String, String>(myMap);
copy.put(x, y); // change the map
myMap = copy;
// you might also consider
myMap = Collections.unmodifiableMap(copy);
// to make sure that the non-thread-safe map will never be mutated
One thing to consider with this pattern is that you may want the myMap
field to be declared as volatile so that all threads will get the most
recen
|
Thread level locale setting in java |
You can use ThreadLocal objects for this purpose. Create a ThreadLocal
object of type Locale like ThreadLocal<Locale> will have thread-local
Locale object , which can be used to get an instance of the Calendar object
using Calendar#getInstance(Locale).
|
Setting a class property on a long running thread |
A Task is not just meant to be used to run code on another thread, it
represents a logical unit of work that can return something once it is
complete.
Your ClassC.GetSerializedDataTable() appears to be a perfect place to make
use of a Task<byte[]> return type:
public class ClassC
{
public DataTable DataTableValue { get; set; }
private Task<byte[]> serializeDataTask;
public void SerializeDataTable()
{
serializeDataTask = Task.Factory.StartNew( () =>
this.DataTableValue.SerializeToByteArray() );
}
public Task<byte[]> GetSerializedDataTable()
{
// You can either throw or start it lazily if SerializeDataTable
hasnt been called yet.
if ( serializeDataTask == null )
throw new InvalidOperationException();
|
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
|
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
|
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,
|
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.
|
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.
|
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.
|
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
|
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.
|
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
|
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
|
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
|
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
|
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
|
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
|
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.
|
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
|
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.
|
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
|
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.
|
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
|
Setting value to a input field using Jquery val not working.I have commented out code setting value in edit() function |
check this fiddle
js fiddle
here is the code that i have modified.
function edit(id){
$("#firstName").val(data[id].firstName);
$("#lastName").val(data[id].lastName);
$("#city").val(data[id].city);
$("#state").val(data[id].state);
$("#pin").val(data[id].pin);
}
|
Linux/Unix - Setting default file/folder permissions using ACL, executable permission not setting? |
It's not setting the execute bit because files are only created with
execute permission if the application explicitly requests it. Since it
makes no sense to make an .html file executable, whatever program created
it did not request execute permission to be added, so it has no execute
permission. Consequently, execute permission from the default ACL
effectively only applies to directories, not to files.
As for why the default group is not set to ftp, this is more subtle. The
default ACL is just that -- an ACL. It's not a default group ownership.
As such it shows up not in ls but in getfacl:
# mkdir public
# setfacl -R -m u::rwx,g:ftp:rwx,d:g:ftp:rwx,o::rx public/
# getfacl public
# file: public
# owner: root
# group: root
user::rwx
group::r-x
group:ftp:rwx
mask::rwx
other::r-x
defa
|
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.
|
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}">
|
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().
|
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.
|
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.
|
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.
|
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.
|
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"
|
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
|
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() {
}
});
}
|
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()
|
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().
|
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
|
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
|