Search Results

Search found 8588 results on 344 pages for 'thread abort'.

Page 44/344 | < Previous Page | 40 41 42 43 44 45 46 47 48 49 50 51  | Next Page >

  • Synchronized Enumerator in C#

    - by Dan Bryant
    I'm putting together a custom SynchronizedCollection<T> class so that I can have a synchronized Observable collection for my WPF application. The synchronization is provided via a ReaderWriterLockSlim, which, for the most part, has been easy to apply. The case I'm having trouble with is how to provide thread-safe enumeration of the collection. I've created a custom IEnumerator<T> nested class that looks like this: private class SynchronizedEnumerator : IEnumerator<T> { private SynchronizedCollection<T> _collection; private int _currentIndex; internal SynchronizedEnumerator(SynchronizedCollection<T> collection) { _collection = collection; _collection._lock.EnterReadLock(); _currentIndex = -1; } #region IEnumerator<T> Members public T Current { get; private set;} #endregion #region IDisposable Members public void Dispose() { var collection = _collection; if (collection != null) collection._lock.ExitReadLock(); _collection = null; } #endregion #region IEnumerator Members object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { var collection = _collection; if (collection == null) throw new ObjectDisposedException("SynchronizedEnumerator"); _currentIndex++; if (_currentIndex >= collection.Count) { Current = default(T); return false; } Current = collection[_currentIndex]; return true; } public void Reset() { if (_collection == null) throw new ObjectDisposedException("SynchronizedEnumerator"); _currentIndex = -1; Current = default(T); } #endregion } My concern, however, is that if the Enumerator is not Disposed, the lock will never be released. In most use cases, this is not a problem, as foreach should properly call Dispose. It could be a problem, however, if a consumer retrieves an explicit Enumerator instance. Is my only option to document the class with a caveat implementer reminding the consumer to call Dispose if using the Enumerator explicitly or is there a way to safely release the lock during finalization? I'm thinking not, since the finalizer doesn't even run on the same thread, but I was curious if there other ways to improve this.

    Read the article

  • Synchronized IEnumerator<T>

    - by Dan Bryant
    I'm putting together a custom SynchronizedCollection<T> class so that I can have a synchronized Observable collection for my WPF application. The synchronization is provided via a ReaderWriterLockSlim, which, for the most part, has been easy to apply. The case I'm having trouble with is how to provide thread-safe enumeration of the collection. I've created a custom IEnumerator<T> nested class that looks like this: private class SynchronizedEnumerator : IEnumerator<T> { private SynchronizedCollection<T> _collection; private int _currentIndex; internal SynchronizedEnumerator(SynchronizedCollection<T> collection) { _collection = collection; _collection._lock.EnterReadLock(); _currentIndex = -1; } #region IEnumerator<T> Members public T Current { get; private set;} #endregion #region IDisposable Members public void Dispose() { var collection = _collection; if (collection != null) collection._lock.ExitReadLock(); _collection = null; } #endregion #region IEnumerator Members object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { var collection = _collection; if (collection == null) throw new ObjectDisposedException("SynchronizedEnumerator"); _currentIndex++; if (_currentIndex >= collection.Count) { Current = default(T); return false; } Current = collection[_currentIndex]; return true; } public void Reset() { if (_collection == null) throw new ObjectDisposedException("SynchronizedEnumerator"); _currentIndex = -1; Current = default(T); } #endregion } My concern, however, is that if the Enumerator is not Disposed, the lock will never be released. In most use cases, this is not a problem, as foreach should properly call Dispose. It could be a problem, however, if a consumer retrieves an explicit Enumerator instance. Is my only option to document the class with a caveat implementer reminding the consumer to call Dispose if using the Enumerator explicitly or is there a way to safely release the lock during finalization? I'm thinking not, since the finalizer doesn't even run on the same thread, but I was curious if there other ways to improve this. EDIT After thinking about this a bit and reading the responses (particular thanks to Hans), I've decided this is definitely a bad idea. The biggest issue actually isn't forgetting to Dispose, but rather a leisurely consumer creating deadlock while enumerating. I now only read-lock long enough to get a copy and return the enumerator for the copy.

    Read the article

  • Variable lenght arguments in log4cxx LOG4CXX_ macros

    - by Horacio
    I am using log4cxx in a big C++ project but I really don't like how log4cxx handles multiple variables when logging: LOG4CXX_DEBUG(logger, "test " << var1 << " and " << var3 " and .....) I prefer using printf like variable length arguments: LOG4CXX_DEBUG(logger, "test %d and %d", var1, var3) So I implemented this small wrapper on top of log4cxx #include <string.h> #include <stdio.h> #include <stdarg.h> #include <log4cxx/logger.h> #include "log4cxx/basicconfigurator.h" const char * log_format(const char *fmt, ...); #define MYLOG_TRACE(logger, fmt, ...) LOG4CXX_TRACE(logger, log_format(fmt, ## __VA_ARGS__)) #define MYLOG_DEBUG(logger, fmt, ...) LOG4CXX_DEBUG(logger, log_format(fmt, ## __VA_ARGS__)) #define MYLOG_INFO(logger, fmt, ...) LOG4CXX_INFO(logger, log_format(fmt, ## __VA_ARGS__)) #define MYLOG_WARN(logger, fmt, ...) LOG4CXX_WARN(logger, log_format(fmt, ## __VA_ARGS__)) #define MYLOG_ERROR(logger, fmt, ...) LOG4CXX_ERROR(logger, log_format(fmt, ## __VA_ARGS__)) #define MYLOG_FATAL(logger, fmt, ...) LOG4CXX_FATAL(logger, log_format(fmt, ## __VA_ARGS__)) static log4cxx::LoggerPtr logger(log4cxx::Logger::getRootLogger()); int main(int argc, char **argv) { log4cxx::BasicConfigurator::configure(); MYLOG_INFO(logger, "Start "); MYLOG_WARN(logger, log_format("In running this in %d threads safe?", 1000)); MYLOG_INFO(logger, "End "); return 0; } const char *log_format(const char *fmt, ...) { va_list va; static char formatted[1024]; va_start(va, fmt); vsprintf(formatted, 1024, fmt, va); va_end(va); return formatted; } And this works perfectly but I know using that static variable (formatted) can become problematic if I start using threads and each thread logging to the same place. I am no expert in log4cxx so I was wondering if the LOG4CXX macros are handling concurrent thread access automatically? or do I have to implement some sort of locking around the log_format method? something that I wan't to avoid due to performance implications. Also I would like to ask why if I replace the vsprintf inside the log_format method with vsnprintf (that is more secure) then I get nothing printed? To compile and test this program (in Ubuntu) use : g++ -o loggertest loggertest.cpp -llog4cxx

    Read the article

  • Run a external program with specified max running time

    - by jack
    I want to execute an external program in each thread of a multi-threaded python program. Let's say max running time is set to 1 second. If started process completes within 1 second, main program capture its output for further processing. If it doesn't finishes in 1 second, main program just terminate it and start another new process. How to implement this?

    Read the article

  • Unmanaged Code calling leads to heavy memory leak!!

    - by konnychen
    Maybe I need change the title as "Unmanaged Code calling leads to heavy memory leak!" The leak is around 30M/hour I think maybe I need complete my code here because the memory leak maybe not from a static string whereas my real code derive this string from external device (see new code attached). so I handle also unmanaged code. Could it be possible the leak comes from unmanaged code? But I freed the resouce by Marshal.FreeCoTaskMem(pos); oThread2 = new Thread(new ThreadStart(Cyclic_Call)); oThread2.Start(); delegate void SetText_lab_Statubar(string text); private void m_SetText_lab_Statubar(string text) { if (this.lab_Statubar.InvokeRequired) { SetText_lab_Statubar d = new SetText_lab_Statubar(m_SetText_lab_Statubar); this.Invoke(d, new object[] { text }); } else { this.lab_Statubar.Text = text; } } private void Cyclic_Call() { do { //... ... ReadMatrixCode(Station6, 0, str_Code); this.m_SetText_lab_Statubar(str_Code[4]); Thread.Sleep(100); } while (!b_AbortThraed); } private void ReadMatrixCode(Station st, int ItemNr, string[] str_Code) { IntPtr pItemStates = IntPtr.Zero; IntPtr pErrors = IntPtr.Zero; int NumItems = itemServerHandles.Length; m_SyncIO.Read(DataSrc, NumItems, itemServerHandles, out pItemStates, out pErrors); // This calls external dll which has some of "out IntPtr" errors = new int[NumItems]; Marshal.Copy(pErrors, errors, 0, NumItems); IntPtr pos = pItemStates; // Now get the read values and check errors for (int dwCount = 0; dwCount < NumItems; dwCount++) { result[dwCount] = (ITEMSTATE)Marshal.PtrToStructure(pos, typeof(ITEMSTATE)); pos = (IntPtr)(pos.ToInt32() + Marshal.SizeOf(typeof(ITEMSTATE))); } // Free allocated COM-ressouces Marshal.FreeCoTaskMem(pItemStates); Marshal.FreeCoTaskMem(pErrors); pItemStates = IntPtr.Zero; pErrors = IntPtr.Zero; } m_syncIO is a class and finally it will call COM component which is defined below [Guid("39C12B52-011E-11D0-9675-1020AFD8ADB3")] [InterfaceType(1)] [ComConversionLoss] public interface ISyncIO { void Read(DATASOURCE dwSource, int dwCount, int[] phServer, out IntPtr ppItemValues, out IntPtr ppErrors); void Write(int dwCount, int[] phServer, object[] pItemValues, out IntPtr ppErrors); }

    Read the article

  • Are +=, |=, &= etc atomic?

    - by SF.
    Are the "modify" operators like +=, |=, &= etc atomic? I know ++ is atomic (if you perform x++; in two different threads "simultaneously", you will always end up with x increased by 2, as opposed to x=x+1 with optimization switched off.) What I wonder is whether variable |= constant, and the likes are thread-safe or do I have to protect them with a mutex? (...or is it CPU-dependent? In this case, how is it on ARM?)

    Read the article

  • Sockets and multithreading

    - by V0idExp
    Hi to all! I have an interesting (to me) problem... There are two threads, one for capturing data from std input and sending it through socket to server, and another one which receives data from blocking socket. So, when there's no reply from server, recv() call waits indefenitely, right? But instead of blocking only its calling thread, it blocks the overall process! Why this thing occurs?

    Read the article

  • ldd output showing shared object file whose function is not called

    - by iamrohitbanga
    I ran ldd command on an executable created by Open MPI. It shows a reference to libpthread.so Using LD_PRELOAD variable I created my own implementation of pthread_create, but from the it output it seems that MPI implementation is not calling pthread_create as I had expected. Why does ldd show pthread so file in output if it is not being used? does Open MPI not use a separate MPI thread for every node to implement the functionality?

    Read the article

  • Do the changes to cpumask using sched_setaffinity() take place immediately

    - by Sukanto
    I am writing a linux kernel module that needs to pin two threads on two different cpus. I am planning to use sched_setaffinity() after exporting it in the kernel. Is there any other exported function for the same ? Also, if I set only 1 CPU in the cpumask, will the thread be moved to that cpu with immediate effect ? If not, how do I enforce the same ? Will it help to call schedule() just after sched_setaffinity() ?

    Read the article

  • Why boost::recursive_mutex is not working as expected?

    - by Kjir
    I have a custom class that uses boost mutexes and locks like this (only relevant parts): template<class T> class FFTBuf { public: FFTBuf(); [...] void lock(); void unlock(); private: T *_dst; int _siglen; int _processed_sums; int _expected_sums; int _assigned_sources; bool _written; boost::recursive_mutex _mut; boost::unique_lock<boost::recursive_mutex> _lock; }; template<class T> FFTBuf<T>::FFTBuf() : _dst(NULL), _siglen(0), _expected_sums(1), _processed_sums(0), _assigned_sources(0), _written(false), _lock(_mut, boost::defer_lock_t()) { } template<class T> void FFTBuf<T>::lock() { std::cerr << "Locking" << std::endl; _lock.lock(); std::cerr << "Locked" << std::endl; } template<class T> void FFTBuf<T>::unlock() { std::cerr << "Unlocking" << std::endl; _lock.unlock(); } If I try to lock more than once the object from the same thread, I get an exception (lock_error): #include "fft_buf.hpp" int main( void ) { FFTBuf<int> b( 256 ); b.lock(); b.lock(); b.unlock(); b.unlock(); return 0; } This is the output: sb@dex $ ./src/test Locking Locked Locking terminate called after throwing an instance of 'boost::lock_error' what(): boost::lock_error zsh: abort ./src/test Why is this happening? Am I understanding some concept incorrectly?

    Read the article

  • Parallelism in .NET – Part 15, Making Tasks Run: The TaskScheduler

    - by Reed
    In my introduction to the Task class, I specifically made mention that the Task class does not directly provide it’s own execution.  In addition, I made a strong point that the Task class itself is not directly related to threads or multithreading.  Rather, the Task class is used to implement our decomposition of tasks.  Once we’ve implemented our tasks, we need to execute them.  In the Task Parallel Library, the execution of Tasks is handled via an instance of the TaskScheduler class. The TaskScheduler class is an abstract class which provides a single function: it schedules the tasks and executes them within an appropriate context.  This class is the class which actually runs individual Task instances.  The .NET Framework provides two (internal) implementations of the TaskScheduler class. Since a Task, based on our decomposition, should be a self-contained piece of code, parallel execution makes sense when executing tasks.  The default implementation of the TaskScheduler class, and the one most often used, is based on the ThreadPool.  This can be retrieved via the TaskScheduler.Default property, and is, by default, what is used when we just start a Task instance with Task.Start(). Normally, when a Task is started by the default TaskScheduler, the task will be treated as a single work item, and run on a ThreadPool thread.  This pools tasks, and provides Task instances all of the advantages of the ThreadPool, including thread pooling for reduced resource usage, and an upper cap on the number of work items.  In addition, .NET 4 brings us a much improved thread pool, providing work stealing and reduced locking within the thread pool queues.  By using the default TaskScheduler, our Tasks are run asynchronously on the ThreadPool. There is one notable exception to my above statements when using the default TaskScheduler.  If a Task is created with the TaskCreationOptions set to TaskCreationOptions.LongRunning, the default TaskScheduler will generate a new thread for that Task, at least in the current implementation.  This is useful for Tasks which will persist for most of the lifetime of your application, since it prevents your Task from starving the ThreadPool of one of it’s work threads. The Task Parallel Library provides one other implementation of the TaskScheduler class.  In addition to providing a way to schedule tasks on the ThreadPool, the framework allows you to create a TaskScheduler which works within a specified SynchronizationContext.  This scheduler can be retrieved within a thread that provides a valid SynchronizationContext by calling the TaskScheduler.FromCurrentSynchronizationContext() method. This implementation of TaskScheduler is intended for use with user interface development.  Windows Forms and Windows Presentation Foundation both require any access to user interface controls to occur on the same thread that created the control.  For example, if you want to set the text within a Windows Forms TextBox, and you’re working on a background thread, that UI call must be marshaled back onto the UI thread.  The most common way this is handled depends on the framework being used.  In Windows Forms, Control.Invoke or Control.BeginInvoke is most often used.  In WPF, the equivelent calls are Dispatcher.Invoke or Dispatcher.BeginInvoke. As an example, say we’re working on a background thread, and we want to update a TextBlock in our user interface with a status label.  The code would typically look something like: // Within background thread work... string status = GetUpdatedStatus(); Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action( () => { statusLabel.Text = status; })); // Continue on in background method .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } This works fine, but forces your method to take a dependency on WPF or Windows Forms.  There is an alternative option, however.  Both Windows Forms and WPF, when initialized, setup a SynchronizationContext in their thread, which is available on the UI thread via the SynchronizationContext.Current property.  This context is used by classes such as BackgroundWorker to marshal calls back onto the UI thread in a framework-agnostic manner. The Task Parallel Library provides the same functionality via the TaskScheduler.FromCurrentSynchronizationContext() method.  When setting up our Tasks, as long as we’re working on the UI thread, we can construct a TaskScheduler via: TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); We then can use this scheduler on any thread to marshal data back onto the UI thread.  For example, our code above can then be rewritten as: string status = GetUpdatedStatus(); (new Task(() => { statusLabel.Text = status; })) .Start(uiScheduler); // Continue on in background method This is nice since it allows us to write code that isn’t tied to Windows Forms or WPF, but is still fully functional with those technologies.  I’ll discuss even more uses for the SynchronizationContext based TaskScheduler when I demonstrate task continuations, but even without continuations, this is a very useful construct. In addition to the two implementations provided by the Task Parallel Library, it is possible to implement your own TaskScheduler.  The ParallelExtensionsExtras project within the Samples for Parallel Programming provides nine sample TaskScheduler implementations.  These include schedulers which restrict the maximum number of concurrent tasks, run tasks on a single threaded apartment thread, use a new thread per task, and more.

    Read the article

  • send sms from background thread in blackberry using j2me

    - by SWATI
    hey i made a lot of search and found some similar types of code. I tried for gsm method 1 gives IllegalArgumentException try { MessageConnection _mc = (MessageConnection)Connector.open("sms://"); TextMessage tm = (TextMessage) _mc.newMessage(MessageConnection.TEXT_MESSAGE); tm.setPayloadText(smsText); tm.setAddress("965xxxxxxx"); _mc.send(tm); _mc.close(); }catch(exception e){} method 2: gives java.lang.error exception try { MessageConnection _mc = (MessageConnection)Connector.open("sms://"); TextMessage tm = (TextMessage) _mc.newMessage(MessageConnection.TEXT_MESSAGE, "//9790XXXXXX"); tm.setPayloadText(text); _mc.send(tm); _mc.close(); }catch(Exception e){} I think the problem is with address i also tried : but no success +91965xxxxxxx , 0091965xxxxxxx , 0965xxxxxxx How my application works---- i have created 2 applications-- 1) Application 1 is a background app that is a System module as well as startup application. 2) Another is a uiapplication the background app runs in background.If there comes an incoming call then a flag value is set in persistent object and after checking that value as true the sms is send to that no from whom call is made.

    Read the article

  • iPhone Gameloop render update from a separate thread

    - by Rich
    Hi, I'm new to iPhone development. I have a game loop setup as follows. (void)CreateGameTick:(NSTimeInterval) in_time { [NSThread detachNewThreadSelector:@selector(GameTick) toTarget:self withObject:nil]; } My basic game tick/render looks like this (void)GameTick { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; CGRect wrect = [self bounds]; while( m_running ) { [self drawRect: wrect]; } [pool release]; } My render function gets called. However nothing gets drawn (I am using Core Graphics to draw some lines on a derived UIView). If I call my update via a timer then all is well and good. Can you tell me why the render fails when done via threads? And is it possible to make it work via threads? Thanks Rich

    Read the article

  • Android ASync task ProgressDialog isn't showing until background thread finishes

    - by jackbot
    I've got an Android activity which grabs an RSS feed from a URL, and uses the SAX parser to stick each item from the XML into an array. This all works fine but, as expected, takes a bit of time, so I want to use AsyncActivity to do it in the background. My code is as follows: class AddTask extends AsyncTask<Void, Item, Void> { protected void onPreExecute() { pDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Retrieving data ...", true); } protected Void doInBackground(Void... unused) { items = parser.getItems(); for (Item it : items) { publishProgress(it); } return(null); } protected void onProgressUpdate(Item... item) { adapter.add(item[0]); } protected void onPostExecute(Void unused) { pDialog.dismiss(); } } Which I call in onCreate() with new AddTask().execute(); The line items = parser.getItems() works fine - items being the arraylist containing each item from the XML. The problem I'm facing is that on starting the activity, the ProgressDialog which i create in onPreExecute() isn't displayed until after the doInBackground() method has finished. i.e. I get a black screen, a long pause, then a completely populated list with the items in. Why is this happening? Why isn't the UI drawing, the ProgressDialog showing, the parser getting the items and incrementally adding them to the list, then the ProgressDialog dismissing?

    Read the article

  • NInject and thread-safety

    - by cbp
    I am having problems with the following class in a multi-threaded environment: public class Foo { [Inject] public IBar InjectedBar { get; set; } public bool NonInjectedProp { get; set; } public void DoSomething() { /* The following line is causing a null-reference exception */ InjectedBar.DoSomething(); } public Foo(bool nonInjectedProp) { /* This line should inject the InjectedBar property */ KernelContainer.Inject(this); NonInjectedProp = nonInjectedProp; } } This is a legacy class which is why I am using property rather than constructor injection. Sometime when the DoSomething() is called the InjectedBar property is null. In a single-threaded application, everything runs fine. How can this be occuring and how can I prevent it?

    Read the article

  • Cygwin socket & thread & other programming issues (some question about Cygwin)

    - by SjB
    I have some question about cygwin : Can I use Cygwin develop socket based code? Does Cygwin have read() and write() functions that work with file descriptors? Can I use Pthread library in Cygwin? Does code that compiles in Cygwin also compile in Linux without any change or with little change? Will an executable file that built by Cygwin run in Linux ? Why does Cygwin not need the linker option -lpthread when I use pthread library? why in #include <iostream> don't I need to use using namespace std; ? Can I work with QT in Cygwin? If so, How?

    Read the article

  • Why is my Tomcat 6 executor thread pool not being used by the connector?

    - by jwegan
    My server.xml looks like the following: <!--The connectors can use a shared executor, you can define one or more named thread pools--> <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" maxThreads="200" minSpareThreads="4"/> <Connector executor="tomcatThreadPool" port="8080" protocol="HTTP/1.1" connectionTimeout="10000" maxKeepAliveRequests="1" redirectPort="8443" /> <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" /> However, in the Tomcat manager (http://localhost/manager/status) it shows to following http-8080: Max threads: -1 Current thread count: -1 Current thread busy: -1 jk-8009: Max threads: 200 Current thread count: 4 Current thread busy: 1 For some reason it looks like http-8080 isn't using the executor even though it is directed too and jk-8009 is using the executor even though it isn't instructed to. Is the manager just misreporting or have I not setup the thread pool correctly?

    Read the article

  • Accessing a cache with a thread? c#

    - by maxp
    Normally i have a static class that reads and writes to HttpContext.Current.Cache However since adding threading to my project, the threads all get null reference exceptions when trying to retrieve this object. Is there any other way i can access it, workarounds or another cache i can use?

    Read the article

< Previous Page | 40 41 42 43 44 45 46 47 48 49 50 51  | Next Page >