Search Results

Search found 1638 results on 66 pages for 'multithreading'.

Page 19/66 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • Non-reentrant C# timer

    - by Oak
    I'm trying to invoke a method f() every t time, but if the previous invocation of f() has not finished yet, wait until it's finished. I've read a bit about the available timers (this is a useful link) but couldn't find any good way of doing what I want, save for manually writing it all. Any help about how to achieve this will be appreciated, though I fear I might not be able to find a simple solution using timers. To clarify, if x is one second, and f() runs the arbitrary durations I've written below, then: Step Operation Time taken 1 wait 1s 2 f() 0.6s 3 wait 0.4s (because f already took 0.6 seconds) 4 f() 10s 5 wait 0s (we're late) 6 f() 0.3s 7 wait 0.7s (we can disregard the debt from step 4) Notice that the nature of this timer is that f() will not need to be safe regarding re-entrance, and a thread pool of size 1 is enough here.

    Read the article

  • perl multiple tasks problem

    - by Alice Wozownik
    I have finished my earlier multithreaded program that uses perl threads and it works on my system. The problem is that on some systems that it needs to run on, thread support is not compiled into perl and I cannot install additional packages. I therefore need to use something other than threads, and I am moving my code to using fork(). This works on my windows system in starting the subtasks. A few problems: How to determine when the child process exits? I created new threads when the thread count was below a certain value, I need to keep track of how many threads are running. For processes, how do I know when one exits so I can keep track of how many exist at the time, incrementing a counter when one is created and decrementing when one exits? Is file I/O using handles obtained with OPEN when opened by the parent process safe in the child process? I need to append to a file for each of the child processes, is this safe on unix as well. Is there any alternative to fork and threads? I tried use Parallel::ForkManager, but that isn't installed on my system (use Parallel::ForkManager; gave an error) and I absolutely require that my perl script work on all unix/windows systems without installing any additional modules.

    Read the article

  • Is RegSetValueEx thread safe?

    - by Brent Newbury
    I suspect that RegSetValueEx is thread safe, but would like some confirmation from the community. If called from multiple threads, will there be any side effects? The RegSetValueEx MSDN documentation doesn't mention thread safety at all.

    Read the article

  • Why is thread local storage so slow?

    - by dsimcha
    I'm working on a custom mark-release style memory allocator for the D programming language that works by allocating from thread-local regions. It seems that the thread local storage bottleneck is causing a huge (~50%) slowdown in allocating memory from these regions compared to an otherwise identical single threaded version of the code, even after designing my code to have only one TLS lookup per allocation/deallocation. This is based on allocating/freeing memory a large number of times in a loop, and I'm trying to figure out if it's an artifact of my benchmarking method. My understanding is that thread local storage should basically just involve accessing something through an extra layer of indirection, similar to accessing a variable via a pointer. Is this incorrect? How much overhead does thread-local storage typically have? Note: Although I mention D, I'm also interested in general answers that aren't specific to D, since D's implementation of thread-local storage will likely improve if it is slower than the best implementations.

    Read the article

  • problem with two .NET threads and hardware access

    - by mack369
    I'm creating an application which communicates with the device via FT2232H USB/RS232 converter. For communication I'm using FTD2XX_NET.dll library from FTDI website. I'm using two threads: first thread continuously reads data from the device the second thread is the main thread of the Windows Form Application I've got a problem when I'm trying to write any data to the device while the receiver's thread is running. The main thread simply hangs up on ftdiDevice.Write function. I tried to synchronize both threads so that only one thread can use Read/Write function at the same time, but it didn't help. Below code responsible for the communication. Note that following functions are methods of FtdiPort class. Receiver's thread private void receiverLoop() { if (this.DataReceivedHandler == null) { throw new BackendException("dataReceived delegate is not set"); } FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK; byte[] readBytes = new byte[this.ReadBufferSize]; while (true) { lock (FtdiPort.threadLocker) { UInt32 numBytesRead = 0; ftStatus = ftdiDevice.Read(readBytes, this.ReadBufferSize, ref numBytesRead); if (ftStatus == FTDI.FT_STATUS.FT_OK) { this.DataReceivedHandler(readBytes, numBytesRead); } else { Trace.WriteLine(String.Format("Couldn't read data from ftdi: status {0}", ftStatus)); Thread.Sleep(10); } } Thread.Sleep(this.RXThreadDelay); } } Write function called from main thread public void Write(byte[] data, int length) { if (this.IsOpened) { uint i = 0; lock (FtdiPort.threadLocker) { this.ftdiDevice.Write(data, length, ref i); } Thread.Sleep(1); if (i != (int)length) { throw new BackendException("Couldnt send all data"); } } else { throw new BackendException("Port is closed"); } } Object used to synchronize two threads static Object threadLocker = new Object(); Method that starts the receiver's thread private void startReceiver() { if (this.DataReceivedHandler == null) { return; } if (this.IsOpened == false) { throw new BackendException("Trying to start listening for raw data while disconnected"); } this.receiverThread = new Thread(this.receiverLoop); //this.receiverThread.Name = "protocolListener"; this.receiverThread.IsBackground = true; this.receiverThread.Start(); } The ftdiDevice.Write function doesn't hang up if I comment following line: ftStatus = ftdiDevice.Read(readBytes, this.ReadBufferSize, ref numBytesRead);

    Read the article

  • ThreadPooler in Spring 2.5.6

    - by MiKu
    My application uses Spring 2.5.6. I have a service that creates explicit threads for some specific task. Triggering of this service call happens through quartz time scheduler. Question : While executing service calls, i want to use some sort of thread pooler that can return me thread instances. Is there any implementations that i can use in Spring?

    Read the article

  • Java Threading Concept Understanding

    - by Nirmal
    Hello All... Recently I have gone through with one simple threading program, which leads me some issues for the related concepts... My sample program code looks like : class NewThread implements Runnable { Thread t; NewThread() { t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread } public void run() { try { for (int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } class ThreadDemo { public static void main(String args[]) { new NewThread(); // create a new thread try { for (int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } Now this program giving me the output as follows : Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting. So, that's very much clear to me. But as soon as I am replacing the object creation code (calling of a NewThread class constructor) to as follows : NewThread nt = new NewThread(); // create a new thread the output becomes a bit varied like as follows : Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Child Thread: 3 Main Thread: 4 Child Thread: 2 Child Thread: 1 Main Thread: 3 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting. And some times it's giving me same output in both the cases. So, i am not getting the exact change in both the scenario. I would like to know that you the variation in the output is coming here ? Thanks in advance...

    Read the article

  • pthread windows event equivalent question

    - by ScaryAardvark
    I have the following code which replicates the windows manual and auto reset events. class event { public: event( bool signalled = false, bool ar = true ) : _auto( ar ), _signalled( signalled ) { pthread_mutex_init( &_mutex, NULL ); pthread_cond_init( &_cond, NULL ); } ~event() { pthread_cond_destroy( &_cond ); pthread_mutex_destroy( &_mutex ); } void set() { pthread_mutex_lock( &_mutex ); // only set and signal if we are unset if ( _signalled == false ) { _signalled = true; pthread_cond_signal( &_cond ); } pthread_mutex_unlock( &_mutex ); } void wait() { pthread_mutex_lock( &_mutex ); while ( _signalled == false ) { pthread_cond_wait( &_cond, &_mutex ); } // if we're an autoreset event, auto reset if ( _auto ) { _signalled = false; } pthread_mutex_unlock( &_mutex ); } void reset() { pthread_mutex_lock( &_mutex ); _signalled = false; pthread_mutex_unlock( &_mutex ); } private: pthread_mutex_t _mutex; pthread_cond_t _cond; bool _signalled; bool _auto; }; My question surrounds the "optimisation" I've put in place in the set() method where I only call pthread_cond_signal() if the event was unsignalled. Is this a valid optimisation or have I introduced some subtle flaw by doing so.

    Read the article

  • PyQt threads and signals - how to properly retrieve values

    - by Cawas
    Using Python 2.5 and PyQt, I couldn't find any question this specific in Python, so sorry if I'm repeating the other Qt referenced questions below, but I couldn't easily understand that C code. I've got two classes, a GUI and a thread, and I'm trying to get return values from the thread. I've used the link in here as base to write my code, which is working just fine. To sum it up and illustrate the question in code here (I don't think this code will run on itself): class MainWindow (QtGui.QWidget): # this is just a reference and not really relevant to the question def __init__ (self, parent = None): QtGui.QWidget.__init__(self, parent) self.thread = Worker() # this does not begin a thread - look at "Worker.run" for mor details self.connect(self.thread, QtCore.SIGNAL('finished()'), self.unfreezeUi) self.connect(self.thread, QtCore.SIGNAL('terminated()'), self.unfreezeUi) self.connect(self.buttonDaemon, QtCore.SIGNAL('clicked()'), self.pressDaemon) # the problem begins below: I'm not using signals, or queue, or whatever, while I believe I should def pressDaemon (self): self.buttonDaemon.setEnabled(False) if self.thread.isDaemonRunning(): self.thread.setDaemonStopSignal(True) self.buttonDaemon.setText('Daemon - converts every %s sec'% args['daemonInterval']) else: self.buttonConvert.setEnabled(False) self.thread.startDaemon() self.buttonDaemon.setText('Stop Daemon') self.buttonDaemon.setEnabled(True) # this whole class is just another reference class Worker (QtCore.QThread): daemonIsRunning = False daemonStopSignal = False daemonCurrentDelay = 0 def isDaemonRunning (self): return self.daemonIsRunning def setDaemonStopSignal (self, bool): self.daemonStopSignal = bool def __init__ (self, parent = None): QtCore.QThread.__init__(self, parent) self.exiting = False self.thread_to_run = None # which def will be running def __del__ (self): self.exiting = True self.thread_to_run = None self.wait() def run (self): if self.thread_to_run != None: self.thread_to_run(mode='continue') def startDaemon (self, mode = 'run'): if mode == 'run': self.thread_to_run = self.startDaemon # I'd love to be able to just pass this as an argument on start() below return self.start() # this will begin the thread # this is where the thread actually begins self.daemonIsRunning = True self.daemonStopSignal = False sleepStep = 0.1 # don't know how to interrupt while sleeping - so the less sleepStep, the faster StopSignal will work # begins the daemon in an "infinite" loop while self.daemonStopSignal == False and not self.exiting: # here, do any kind of daemon service delay = 0 while self.daemonStopSignal == False and not self.exiting and delay < args['daemonInterval']: time.sleep(sleepStep) # delay is actually set by while, but this holds for N second delay += sleepStep # daemon stopped, reseting everything self.daemonIsRunning = False self.emit(QtCore.SIGNAL('terminated')) Tho it's quite big, I hope this is pretty clear. The main point is on def pressDaemon. Specifically all 3 self.thread calls. The last one, self.thread.startDaemon() is just fine, and exactly as the example. I doubt that represents any issue. The problem is being able to set the Daemon Stop Signal and retrieve the value if it's running. I'm not sure that it's possible to set a stop signal on QtCore.QtThread, because I've tried doing the same way and it didn't work. But I'm pretty sure it's not possible to retrieve a return result from the emit. So, there it is. I'm using direct calls to the thread class, and I'm almost positive that's not a good design and will probably fail when running under stress. I read about that queue, but I'm not sure it's the proper solution here, or if I should be using Qt at all, since this is Python. And just maybe there's nothing wrong with the way I'm doing.

    Read the article

  • Writing to a log4net FileAppender with multiple threads performance problems

    - by Wayne
    TickZoom is a very high performance app which uses it's own parallelization library and multiple O/S threads for smooth utilization of multi-core computers. The app hits a bottleneck where users need to write information to a LogAppender from separate O/S threads. The FileAppender uses the MinimalLock feature so that each thread can lock and write to the file and then release it for the next thread to write. If MinimalLock gets disabled, log4net reports errors about the file being already locked by another process (thread). A better way for log4net to do this would be to have a single thread that takes care of writing to the FileAppender and any other threads simply add their messages to a queue. In that way, MinimalLock could be disabled to greatly improve performance of logging. Additionally, the application does a lot of CPU intensive work so it will also improve performance to use a separate thread for writing to the file so the CPU never waits on the I/O to complete. So the question is, does log4net already offer this feature? If so, how do you do enable threaded writing to a file? Is there another, more advanced appender, perhaps? If not, then since log4net is already wrapped in the platform, that makes it possible to implement a separate thread and queue for this purpose in the TickZoom code. Sincerely, Wayne

    Read the article

  • Safe to update separate regions of a BufferedImage in separate threads?

    - by finnw
    I have a collection of BufferedImage instances, one main image and some subimages created by calling getSubImage on the main image. The subimages do not overlap. I am also making modifications to the subimage and I want to split this into multiple threads, one per subimage. From my understanding of how BufferedImage, Raster and DataBuffer work, this should be safe because: Each instance of BufferedImage (and its respective WritableRaster) is accessed from only one thread. The shared ColorModel is immutable The DataBuffer has no fields that can be modified (the only thing that can change is elements of the backing array.) Modifying disjoint segments of an array in separate threads is safe. However I cannot find anything in the documentation that says that it is definitely safe to do this. Can I assume it is safe? I know that it is possible to work on copies of the child Rasters but I would prefer to avoid this because of memory constraints. Otherwise, is it possible to make the operation thread-safe without copying regions of the parent image?

    Read the article

  • C# TraceSource class in multithreaded application

    - by matti
    msdn: "Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe." it contains only instance methods. How should I use it in a way that all activity gets recorder by TextWriterTraceListener to a text file. Is one static member which all threads use (by calling) TraceEvent-method safe. (I've kind of asked this question in http://stackoverflow.com/questions/1901086/how-to-instantiate-c-tracesources-to-log-multithreaded-asp-net-2-0-web-applica, but I cannot just believe if somebody just says it's OK despite the documentation).

    Read the article

  • Using ftplib for multithread uploads

    - by Arty
    I'm trying to do multithread uploads, but get errors. I guessed that maybe it's impossible to use multithreads with ftplib? Here comes my code: class myThread (threading.Thread): def __init__(self, threadID, src, counter, image_name): self.threadID = threadID self.src = src self.counter = counter self.image_name = image_name threading.Thread.__init__(self) def run(self): uploadFile(self.src, self.image_name) def uploadFile(src, image_name): f = open(src, "rb") ftp.storbinary('STOR ' + image_name, f) f.close() ftp = FTP('host') # connect to host, default port ftp.login() # user anonymous, passwd anonymous@ dirname = "/home/folder/" i = 1 threads = [] for image in os.listdir(dirname): if os.path.isfile(dirname + image): thread = myThread(i , dirname + image, i, image ) thread.start() threads.append( thread ) i += 1 for t in threads: t.join() Get bunch of ftplib errors like raise error_reply, resp error_reply: 200 Type set to I If I try to upload one by one, everything works fine

    Read the article

  • Is this (Lock-Free) Queue Implementation Thread-Safe?

    - by Hosam Aly
    I am trying to create a lock-free queue implementation in Java, mainly for personal learning. The queue should be a general one, allowing any number of readers and/or writers concurrently. Would you please review it, and suggest any improvements/issues you find? Thank you. import java.util.concurrent.atomic.AtomicReference; public class LockFreeQueue<T> { private static class Node<E> { E value; volatile Node<E> next; Node(E value) { this.value = value; } } private AtomicReference<Node<T>> head, tail; public LockFreeQueue() { // have both head and tail point to a dummy node Node<T> dummyNode = new Node<T>(null); head = new AtomicReference<Node<T>>(dummyNode); tail = new AtomicReference<Node<T>>(dummyNode); } /** * Puts an object at the end of the queue. */ public void putObject(T value) { Node<T> newNode = new Node<T>(value); Node<T> prevTailNode = tail.getAndSet(newNode); prevTailNode.next = newNode; } /** * Gets an object from the beginning of the queue. The object is removed * from the queue. If there are no objects in the queue, returns null. */ public T getObject() { Node<T> headNode, valueNode; // move head node to the next node using atomic semantics // as long as next node is not null do { headNode = head.get(); valueNode = headNode.next; // try until the whole loop executes pseudo-atomically // (i.e. unaffected by modifications done by other threads) } while (valueNode != null && !head.compareAndSet(headNode, valueNode)); T value = (valueNode != null ? valueNode.value : null); // release the value pointed to by head, keeping the head node dummy if (valueNode != null) valueNode.value = null; return value; }

    Read the article

  • @synchronized doesn't work in static library

    - by David Beck
    For some reason, when I try to use @synchronized in a static library for the iPhone, I get an error in the project that uses it: Undefined symbols: "___restore_vfp_d8_d15_regs", referenced from: -[GVInbox addConversation:] in libGVKit.a(GVInbox.o) "___save_vfp_d8_d15_regs", referenced from: -[GVInbox addConversation:] in libGVKit.a(GVInbox.o) ld: symbol(s) not found collect2: ld returned 1 exit status

    Read the article

  • How to set WCF threads to schedual differently

    - by Gilad
    Hi, I'm running a winservice that has 2 main objectives. Execute/Handle exposed webmethods. Run Inner processes that consume allot of CPU. The problem is that when I execute many inner processes |(as tasks) that are queued to the threadpool or taskpool, the execution of the webmethods takes much more time as WCF also queues its executions to the same threadpool. This even happens when setting the inner processes task priority to lowest and setting the webmethods thread priority to heights. I hoped that Framework 4.0 would improve this, and they have, but still it takes quite allot of time for the system to handle the WCF queued tasks if the CPU is handling other inner tasks. Is it possible to change the Threadpool that WCF uses to a different one? Is it possible to manually change the task queue (global task queue, local task queue). Is it possible to manually handle 2 task queues that behave differently ? Any help in the subject would be appropriated. Gilad.

    Read the article

  • C++ Mutexes and STL Lists Across Subclasses

    - by Genesis
    I am currently writing a multi-threaded C++ server using Poco and am now at the point where I need to be keeping information on which users are connected, how many connections each of them have, and given it is a proxy server, where each of those connections are proxying through to. For this purpose I have created a ServerStats class which holds an STL list of ServerUser objects. The ServerStats class includes functions which can add and remove objects from the list as well as find a user in the list an return a pointer to them so I can access member functions within any given ServerUser object in the list. The ServerUser class contains an STL list of ServerConnection objects and much like the ServerStats class it contains functions to add, remove and find elements within this list. Now all of the above is working but I am now trying to make it threadsafe. I have defined a Poco::FastMutex within the ServerStats class and can lock/unlock this in the appropriate places so that STL containers are not modified at the same time as being searched for example. I am however having an issue setting up mutexes within the ServerUser class and am getting the following compiler error: /root/poco/Foundation/include/Poco/Mutex.h: In copy constructor âServerUser::ServerUser(const ServerUser&)â: src/SocksServer.cpp:185: instantiated from âvoid __gnu_cxx::new_allocator<_Tp::construct(_Tp*, const _Tp&) [with _Tp = ServerUser]â /usr/include/c++/4.4/bits/stl_list.h:464: instantiated from âstd::_List_node<_Tp* std::list<_Tp, _Alloc::_M_create_node(const _Tp&) [with _Tp = ServerUser, _Alloc = std::allocator]â /usr/include/c++/4.4/bits/stl_list.h:1407: instantiated from âvoid std::list<_Tp, _Alloc::_M_insert(std::_List_iterator<_Tp, const _Tp&) [with _Tp = ServerUser, _Alloc = std::allocator]â /usr/include/c++/4.4/bits/stl_list.h:920: instantiated from âvoid std::list<_Tp, _Alloc::push_back(const _Tp&) [with _Tp = ServerUser, _Alloc = std::allocator]â src/SocksServer.cpp:301: instantiated from here /root/poco/Foundation/include/Poco/Mutex.h:164: error: âPoco::FastMutex::FastMutex(const Poco::FastMutex&)â is private src/SocksServer.cpp:185: error: within this context In file included from /usr/include/c++/4.4/x86_64-linux-gnu/bits/c++allocator.h:34, from /usr/include/c++/4.4/bits/allocator.h:48, from /usr/include/c++/4.4/string:43, from /root/poco/Foundation/include/Poco/Bugcheck.h:44, from /root/poco/Foundation/include/Poco/Foundation.h:147, from /root/poco/Net/include/Poco/Net/Net.h:45, from /root/poco/Net/include/Poco/Net/TCPServerParams.h:43, from src/SocksServer.cpp:1: /usr/include/c++/4.4/ext/new_allocator.h: In member function âvoid __gnu_cxx::new_allocator<_Tp::construct(_Tp*, const _Tp&) [with _Tp = ServerUser]â: /usr/include/c++/4.4/ext/new_allocator.h:105: note: synthesized method âServerUser::ServerUser(const ServerUser&)â first required here src/SocksServer.cpp: At global scope: src/SocksServer.cpp:118: warning: âstd::string getWord(std::string)â defined but not used make: * [/root/poco/SocksServer/obj/Linux/x86_64/debug_shared/SocksServer.o] Error 1 The code for the ServerStats, ServerUser and ServerConnection classes is below: class ServerConnection { public: bool continue_connection; int bytes_in; int bytes_out; string source_address; string destination_address; ServerConnection() { continue_connection = true; } ~ServerConnection() { } }; class ServerUser { public: string username; int connection_count; string client_ip; ServerUser() { } ~ServerUser() { } ServerConnection* addConnection(string source_address, string destination_address) { //FastMutex::ScopedLock lock(_connection_mutex); ServerConnection connection; connection.source_address = source_address; connection.destination_address = destination_address; client_ip = getWord(source_address, ":"); _connections.push_back(connection); connection_count++; return &_connections.back(); } void removeConnection(string source_address) { //FastMutex::ScopedLock lock(_connection_mutex); for(list<ServerConnection>::iterator it = _connections.begin(); it != _connections.end(); it++) { if(it->source_address == source_address) { it = _connections.erase(it); connection_count--; } } } void disconnect() { //FastMutex::ScopedLock lock(_connection_mutex); for(list<ServerConnection>::iterator it = _connections.begin(); it != _connections.end(); it++) { it->continue_connection = false; } } list<ServerConnection>* getConnections() { return &_connections; } private: list<ServerConnection> _connections; //UNCOMMENTING THIS LINE BREAKS IT: //mutable FastMutex _connection_mutex; }; class ServerStats { public: int current_users; ServerStats() { current_users = 0; } ~ServerStats() { } ServerUser* addUser(string username) { FastMutex::ScopedLock lock(_user_mutex); for(list<ServerUser>::iterator it = _users.begin(); it != _users.end(); it++) { if(it->username == username) { return &(*it); } } ServerUser newUser; newUser.username = username; _users.push_back(newUser); current_users++; return &_users.back(); } void removeUser(string username) { FastMutex::ScopedLock lock(_user_mutex); for(list<ServerUser>::iterator it = _users.begin(); it != _users.end(); it++) { if(it->username == username) { _users.erase(it); current_users--; break; } } } ServerUser* getUser(string username) { FastMutex::ScopedLock lock(_user_mutex); for(list<ServerUser>::iterator it = _users.begin(); it != _users.end(); it++) { if(it->username == username) { return &(*it); } } return NULL; } private: list<ServerUser> _users; mutable FastMutex _user_mutex; }; Now I have never used C++ for a project of this size or mutexes for that matter so go easy please :) Firstly, can anyone tell me why the above is causing a compiler error? Secondly, can anyone suggest a better way of storing the information I require? Bear in mind that I need to update this info whenever connections come or go and it needs to be global to the whole server.

    Read the article

  • Spinlocks, How Much Useful Are They?

    - by unknown
    How often do you find yourself actually using spinlocks in your code? How common is it to come across a situation where using a busy loop actually outperforms the usage of locks? Personally, when I write some sort of code that requires thread safety, I tend to benchmark it with different synchronization primitives, and as far as it goes, it seems like using locks gives better performance than using spinlocks. No matter for how little time I actually hold the lock, the amount of contention I receive when using spinlocks is far greater than the amount I get from using locks (of course, I run my tests on a multiprocessor machine). I realize that it's more likely to come across a spinlock in "low-level" code, but I'm interested to know whether you find it useful in even a more high-level kind of programming?

    Read the article

  • How to Schedule Method call in Objective C

    - by user359277
    Hi, I am try to do multi-threading in Objective C. What I want to do now is that, for some instance of objects, I want to have to way to call some function 5 seconds later. How can I do that? In Coco 2D, it's very easy to do it. They have something called scheduler. In Objective C, how to do it please? Thanks

    Read the article

  • iphone - memory leaks in separate thread

    - by Brodie4598
    I create a second thread to call a method that downloads several images using: [NSThread detachNewThreadSelector:@selector(downloadImages) toTarget:self withObject:nil]; It works fine but I get a long list of leaks in the log similar to: 2010-04-18 00:48:12.287 FS Companion[11074:650f] * _NSAutoreleaseNoPool(): Object 0xbec2640 of class NSCFString autoreleased with no pool in place - just leaking Stack: (0xa58af 0xdb452 0x5e973 0x5e770 0x11d029 0x517fa 0x51708 0x85f2 0x3047d 0x30004 0x99481fbd 0x99481e42) 2010-04-18 00:48:12.288 FS Companion[11074:650f] * _NSAutoreleaseNoPool(): Object 0xbe01510 of class NSCFString autoreleased with no pool in place - just leaking Stack: (0xa58af 0xdb452 0x5e7a6 0x11d029 0x517fa 0x51708 0x85f2 0x3047d 0x30004 0x99481fbd 0x99481e42) 2010-04-18 00:48:12.289 FS Companion[11074:650f] * _NSAutoreleaseNoPool(): Object 0xbde6720 of class NSCFString autoreleased with no pool in place - just leaking Stack: (0xa58af 0xdb452 0x5ea73 0x5e7c2 0x11d029 0x517fa 0x51708 0x85f2 0x3047d 0x30004 0x99481fbd 0x99481e42) Can someone help me understand the problem?

    Read the article

  • Does PHP have job control like bash does?

    - by Andrew
    Hello, does PHP support something like ampersand in bash (forking)? Let's say I wanted to use cURL on 2 web pages concurrently, so script doesn't have to wait before first cURL command finnishes, how could one achieve that in PHP? Something like this in bash: curl www.google.com & curl www.yahoo.com & wait

    Read the article

  • form update too expensive to be executed in Winform.Timer.Tick

    - by Abruzzo Forte e Gentile
    Hi all I have a WinForm drawing a chart from available data. I programmed it so that every 1 secong the Winform.Timer.Tick event calls a function that: will dequeue all data available will add new points on the chart Right now data to be plotted is really huge and it takes a lot of time to be executed so to update my form. Also Winform.Timer.Tick relies on WM_TIMER , so it executes in the same thread of the Form. Theses 2 things are making my form very UNresponsive. What can I do to solve this issue? I thought the following: moving away from usage of Winform.Timer and start using a System.Threading.Timer use the IsInvokeRequired pattern so I will rely on the .NET ThreadPool. Since I have lots of data, is this a good idea? I have fear that at some point also the ThreadPool will be too long or too big. Can you give me your suggestion about my issue? Thank you very much! AFG

    Read the article

  • Application.Current.Shutdown() vs. Application.Current.Dispatcher.BeginInvokeShutdown()

    - by Daniel Rose
    First a bit of background: I have a WPF application, which is a GUI-front-end to a legacy Win32-application. The legacy app runs as DLL in a separate thread. The commands the user chooses in the UI are invoked on that "legacy thread". If the "legacy thread" finishes, the GUI-front-end cannot do anything useful anymore, so I need to shutdown the WPF-application. Therefore, at the end of the thread's method, I call Application.Current.Shutdown(). Since I am not on the main thread, I need to invoke this command. However, then I noticed that the Dispatcher also has BeginInvokeShutdown() to shutdown the dispatcher. So my question is: What is the difference between invoking Application.Current.Shutdown(); and calling Application.Current.Dispatcher.BeginInvokeShutdown();

    Read the article

  • Assigning a property across threads

    - by Mike
    I have set a property across threads before and I found this post http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the-t about getting a property. I think my issue with the code below is setting the variable to the collection is an object therefore on the heap and therefore is just creating a pointer to the same object So my question is besides creating a deep copy, or copying the collection into a different List object is there a better way to do the following to aviod the error during the for loop. Cross-thread operation not valid: Control 'lstProcessFiles' accessed from a thread other than the thread it was created on. Code: private void btnRunProcess_Click(object sender, EventArgs e) { richTextBox1.Clear(); BackgroundWorker bg = new BackgroundWorker(); bg.DoWork += new DoWorkEventHandler(bg_DoWork); bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted); bg.RunWorkerAsync(lstProcessFiles.SelectedItems); } void bg_DoWork(object sender, DoWorkEventArgs e) { WorkflowEngine engine = new WorkflowEngine(); ListBox.SelectedObjectCollection selectedCollection=null; if (lstProcessFiles.InvokeRequired) { // Try #1 selectedCollection = (ListBox.SelectedObjectCollection) this.Invoke(new GetSelectedItemsDelegate(GetSelectedItems), new object[] { lstProcessFiles }); // Try #2 //lstProcessFiles.Invoke( // new MethodInvoker(delegate { // selectedCollection = lstProcessFiles.SelectedItems; })); } else { selectedCollection = lstProcessFiles.SelectedItems; } // *********Same Error on this line******************** // Cross-thread operation not valid: Control 'lstProcessFiles' accessed // from a thread other than the thread it was created on. foreach (string l in selectedCollection) { if (engine.LoadProcessDocument(String.Format(@"C:\TestDirectory\{0}", l))) { try { engine.Run(); WriteStep(String.Format("Ran {0} Succussfully", l)); } catch { WriteStep(String.Format("{0} Failed", l)); } engine.PrintProcess(); WriteStep(String.Format("Rrinted {0} to debug", l)); } } } private delegate void WriteDelegate(string p); private delegate ListBox.SelectedObjectCollection GetSelectedItemsDelegate(ListBox list); private ListBox.SelectedObjectCollection GetSelectedItems(ListBox list) { return list.SelectedItems; }

    Read the article

  • Strange behaviour of code inside TransactionScope?

    - by Krishna
    We are facing a very complex issue in our production application. We have a WCF method which creates a complex Entity in the database with all its relation. public void InsertEntity(Entity entity) { using(TransactionScope scope = new TransactionScope()) { EntityDao.Create(entity); } } EntityDao.Create(entity) method is very complex and has huge pieces of logic. During the entire process of creation it creates several child entities and also have several queries to database. During the entire WCF request of entity creation usually Connection is maintained in a ThreadStatic variable and reused by the DAOs. Although some of the queries in DAO described in step 2 uses a new connection and closes it after use. Overall we have seen that the above process behaviour is erratic. Some of the queries in the inner DAO does not even return actual data from the database? The same query when run to the actaul data store gives correct result. What can be possible reason of this behaviour?

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >