Search Results

Search found 11135 results on 446 pages for 'thread safe'.

Page 7/446 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • android shut-down errors / thread problems

    - by iQue
    Im starting to deal with some stuff in my game that I thought were "minor problems" and one of these are that I get an error every time I shut down my game that looks like this: 09-05 21:40:58.320: E/AndroidRuntime(30401): FATAL EXCEPTION: Thread-4898 09-05 21:40:58.320: E/AndroidRuntime(30401): java.lang.NullPointerException 09-05 21:40:58.320: E/AndroidRuntime(30401): at nielsen.happy.shooter.MainGamePanel.render(MainGamePanel.java:94) 09-05 21:40:58.320: E/AndroidRuntime(30401): at nielsen.happy.shooter.MainThread.run(MainThread.java:101) on these lines is my GameViews rendering-method and the line in my Thread that calls my GameViews rendering-method. Im guessing Something in my surfaceDestroyed(SurfaceHolder holder) is wrong, or maybe Im not ending the tread in the right place. My surfaceDestroyed-method: public void surfaceDestroyed(SurfaceHolder holder) { Log.d(TAG, "Surface is being destroyed"); boolean retry = true; ((MainThread)thread).setRunning(false); while (retry) { try { ((MainThread)thread).join(); retry = false; } catch (InterruptedException e) { } } Log.d(TAG, "Thread was shut down cleanly"); } Also, In my activity for this View my onPaus, onDestoy and onStop are empty, do I maybe need to add something there? The crash occurs when I press my home-button on the phone, or any other button that makes the game stop. But as I understand it the onPaus is called when you press the Home-button.. This is really new territory for me so Im sorry if im missing something obvious or something really big. adding my surfaceCreated method asweel since that is where I start this thread: public void surfaceCreated(SurfaceHolder holder) { controls = new GameControls(this); setOnTouchListener(controls); timer1.schedule(new Task(this), 0, delay1); thread.setRunning(true); thread.start(); } and aslong as this is running, my game is rendering and updating.

    Read the article

  • Java Stop Server Thread

    - by ikurtz
    the following code is server code in my app: private int serverPort; private Thread serverThread = null; public void networkListen(int port){ serverPort = port; if (serverThread == null){ Runnable serverRunnable = new ServerRunnable(); serverThread = new Thread(serverRunnable); serverThread.start(); } else { } } public class ServerRunnable implements Runnable { public void run(){ try { //networkConnected = false; //netMessage = "Listening for Connection"; //networkMessage = new NetworkMessage(networkConnected, netMessage); //setChanged(); //notifyObservers(networkMessage); ServerSocket serverSocket = new ServerSocket(serverPort, backlog); commSocket = serverSocket.accept(); serverSocket.close(); serverSocket = null; //networkConnected = true; //netMessage = "Connected: " + commSocket.getInetAddress().getHostAddress() + ":" + //commSocket.getPort(); //networkMessage = new NetworkMessage(networkConnected, netMessage); //setChanged(); //notifyObservers(networkMessage); } catch (IOException e){ //networkConnected = false; //netMessage = "ServerRunnable Network Unavailable"; //System.out.println(e.getMessage()); //networkMessage = new NetworkMessage(networkConnected, netMessage); //setChanged(); //notifyObservers(networkMessage); } } } The code sort of works i.e. if im attempting a straight connection both ends communicate and update. The issue is while im listening for a connection if i want to quit listening then the server thread continues running and causes problems. i know i should not use .stop() on a thread so i was wondering what the solution would look like with this in mind? EDIT: commented out unneeded code.

    Read the article

  • Thread-local storage segfaults on NetBSD only?

    - by bortzmeyer
    Trying to run a C++ program, I get segmentation faults which appear to be specific to NetBSD. Bert Hubert wrote the simple test program (at the end of this message) and, indeed, it crashes only on NetBSD. % uname -a NetBSD golgoth 5.0.1 NetBSD 5.0.1 (GENERIC) #0: Thu Oct 1 15:46:16 CEST 2009 +stephane@golgoth:/usr/obj/sys/arch/i386/compile/GENERIC i386 % g++ --version g++ (GCC) 4.1.3 20080704 prerelease (NetBSD nb2 20081120) Copyright (C) 2006 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. % gdb thread-local-storage-powerdns GNU gdb 6.5 Copyright (C) 2006 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i386--netbsdelf"... (gdb) run Starting program: /home/stephane/Programmation/C++/essais/thread-local-storage-powerdns Program received signal SIGSEGV, Segmentation fault. 0x0804881b in main () at thread-local-storage-powerdns.cc:20 20 t_a = new Bogo('a'); (gdb) On other Unix, it works fine. Is there a known issue in NetBSD with C++ thread-local storage? #include <stdio.h> class Bogo { public: explicit Bogo(char a) { d_a = a; } char d_a; }; __thread Bogo* t_a; int main() { t_a = new Bogo('a'); Bogo* b = t_a; printf("%c\n", b->d_a); }

    Read the article

  • Return Double from Boost thread

    - by Benedikt Wutzi
    Hi I have an Boost thread which should return a double. The function looks like this: void analyser::findup(const double startwl, const double max, double &myret){ this->data.begin(); for(int i = (int)data.size() ; i >= 0;i--){ if(this->data[i].lambda > startwl){ if(this->data[i].db >= (max-30)) { myret = this->data[i+1].lambda; std::cout <<"in thread " << myret << std::endl; return; } } } } this function is called by another function: void analyser::start_find_up(const double startwl, const double max){ double tmp = -42.0; boost::thread up(&analyser::findup,*this, startwl,max,tmp); std::cout << "before join " << tmp << std::endl; up.join(); std::cout << "after join " << tmp << std::endl; } Anyway I've tried and googled almost anything but i can't get it to return a value. The output looks like this right now. before join -42 in thread 843.487 after join -42 Thanks for any help.

    Read the article

  • Thread-safety of read-only memory access

    - by Edmund
    I've implemented the Barnes-Hut gravity algorithm in C as follows: Build a tree of clustered stars. For each star, traverse the tree and apply the gravitational forces from each applicable node. Update the star velocities and positions. Stage 2 is the most expensive stage, and so is implemented in parallel by dividing the set of stars. E.g. with 1000 stars and 2 threads, I have one thread processing the first 500 stars and the second thread processing the second 500. In practice this works: it speeds the computation by about 30% with two threads on a two-core machine, compared to the non-threaded version. Additionally, it yields the same numerical results as the original non-threaded version. My concern is that the two threads are accessing the same resource (namely, the tree) simultaneously. I have not added any synchronisation to the thread workers, so it's likely they will attempt to read from the same location at some point. Although access to the tree is strictly read-only I am not 100% sure it's safe. It has worked when I've tested it but I know this is no guarantee of correctness! Questions Do I need to make a private copy of the tree for each thread? Even if it is safe, are there performance problems of accessing the same memory from multiple threads?

    Read the article

  • Passing variables from a thread to another form using C#

    - by kirstom14
    Hi, I am trying to pass 2 variables from a thread, in the MainForm, to another form, but when doing so an error occurs. private void TrackingThread( ) { float targetX = 0; float targetY = 0; while ( true ) { camera1Acquired.WaitOne( ); camera2Acquired.WaitOne( ); lock ( this ) { // stop the thread if it was signaled if ( ( x1 == -1 ) && ( y1 == -1 ) && ( x2 == -1 ) && ( y2 == -1 ) ) { break; } // get middle point targetX = ( x1 + x2 ) / 2; targetY = ( y1 + y2 ) / 2; } if (directionForm != null) { directionForm.RunMotors(targetX, targetY); } } } In the form, directionForm, I am simply displaying the variables targetX and targetY. The code for the directionForm.RunMotors() is the following: public void RunMotors(float x, float y) { label1.Text = "X-ordinate " + x.ToString(); label2.Text = "Y-ordinate " + y.ToString(); } The error happen when I am trying to display the two variables: "InvalidOperationException was unhandled Cross-threading operation not valid: Control label1 accessed from a thread other than . the thread it was created on" What shall I do??? Thanks in advance

    Read the article

  • Need a Java based interruptible timer thread

    - by LambeauLeap
    I have a Main Program which is running a script on the target device(smart phone) and in a while loop waiting for stdout messages. However in this particular case, some of the heartbeat messages on the stdout could be spaced almost 45secs to a 1minute apart. something like: stream = device.runProgram(RESTORE_LOGS, new String[] {}); stream.flush(); String line = stream.readLine(); while (line.compareTo("") != 0) { reporter.commentOnJob(jobId, line); line = stream.readLine(); } So, I want to be a able to start a new interruptible thread after reading line from stdout with a required a sleep window. Upon being able to read a new line, I want to be able to interrupt/stop(having trouble killing the process), handle the newline of stdout text and restart a process. And it the event I am not able to read a line within the timer window(say 45secs) I want to a way to get out of my while loop either. I already tried the thread.run, thread.interrupt approach. But having trouble killing and starting a new thread. Is this the best way out or am I missing something obvious?

    Read the article

  • Simple thread-safe non-blocking file logger class in c#

    - by Jason Renlan
    I have a web application, that will log some information to a file. I am looking for a simple thread-safe non-blocking file logger class in c#. I have little experience with threading. I known there are great logging components out there like log4Net, Enterprise Library Logging Block, ELMAH, but I do not want an external dependence for my application. I was thinking about using this queue implementation http://www.codeproject.com/KB/cpp/lockfreeq.aspx

    Read the article

  • how do you make a "concurrent queue safe" lazy loader (singleton manager) in objective-c

    - by Rich
    Hi, I made this class that turns any object into a singleton, but I know that it's not "concurrent queue safe." Could someone please explain to me how to do this, or better yet, show me the code. To be clear I want to know how to use this with operation queues and dispatch queues (NSOperationQueue and Grand Central Dispatch) on iOS. Thanks in advance, Rich EDIT: I had an idea for how to do it. If someone could confirm it for me I'll do it and post the code. The idea is that proxies make queues all on their own. So if I make a mutable proxy (like Apple does in key-value coding/observing) for any object that it's supposed to return, and always return the same proxy for the same object/identifier pair (using the same kind of lazy loading technique as I used to create the singletons), the proxies would automatically queue up the any messages to the singletons, and make it totally thread safe. IMHO this seems like a lot of work to do, so I don't want to do it if it's not gonna work, or if it's gonna slow my apps down to a crawl. Here's my non-thread safe code: RMSingletonCollector.h // // RMSingletonCollector.h // RMSingletonCollector // // Created by Rich Meade-Miller on 2/11/11. // Copyright 2011 Rich Meade-Miller. All rights reserved. // #import <Foundation/Foundation.h> #import "RMWeakObjectRef.h" struct RMInitializerData { // The method may take one argument. // required SEL designatedInitializer; // data to pass to the initializer or nil. id data; }; typedef struct RMInitializerData RMInitializerData; RMInitializerData RMInitializerDataMake(SEL initializer, id data); @interface NSObject (SingletonCollector) // Returns the selector and data to pass to it (if the selector takes an argument) for use when initializing the singleton. // If you override this DO NOT call super. + (RMInitializerData)designatedInitializerForIdentifier:(NSString *)identifier; @end @interface RMSingletonCollector : NSObject { } + (id)collectionObjectForType:(NSString *)className identifier:(NSString *)identifier; + (id<RMWeakObjectReference>)referenceForObjectOfType:(NSString *)className identifier:(NSString *)identifier; + (void)destroyCollection; + (void)destroyCollectionObjectForType:(NSString *)className identifier:(NSString *)identifier; @end // ==--==--==--==--==Notifications==--==--==--==--== extern NSString *const willDestroySingletonCollection; extern NSString *const willDestroySingletonCollectionObject; RMSingletonCollector.m // // RMSingletonCollector.m // RMSingletonCollector // // Created by Rich Meade-Miller on 2/11/11. // Copyright 2011 Rich Meade-Miller. All rights reserved. // #import "RMSingletonCollector.h" #import <objc/objc-runtime.h> NSString *const willDestroySingletonCollection = @"willDestroySingletonCollection"; NSString *const willDestroySingletonCollectionObject = @"willDestroySingletonCollectionObject"; RMInitializerData RMInitializerDataMake(SEL initializer, id data) { RMInitializerData newData; newData.designatedInitializer = initializer; newData.data = data; return newData; } @implementation NSObject (SingletonCollector) + (RMInitializerData)designatedInitializerForIdentifier:(NSString *)identifier { return RMInitializerDataMake(@selector(init), nil); } @end @interface RMSingletonCollector () + (NSMutableDictionary *)singletonCollection; + (void)setSingletonCollection:(NSMutableDictionary *)newSingletonCollection; @end @implementation RMSingletonCollector static NSMutableDictionary *singletonCollection = nil; + (NSMutableDictionary *)singletonCollection { if (singletonCollection != nil) { return singletonCollection; } NSMutableDictionary *collection = [[NSMutableDictionary alloc] initWithCapacity:1]; [self setSingletonCollection:collection]; [collection release]; return singletonCollection; } + (void)setSingletonCollection:(NSMutableDictionary *)newSingletonCollection { if (newSingletonCollection != singletonCollection) { [singletonCollection release]; singletonCollection = [newSingletonCollection retain]; } } + (id)collectionObjectForType:(NSString *)className identifier:(NSString *)identifier { id obj; NSString *key; if (identifier) { key = [className stringByAppendingFormat:@".%@", identifier]; } else { key = className; } if (obj = [[self singletonCollection] objectForKey:key]) { return obj; } // dynamic creation. // get a class for Class classForName = NSClassFromString(className); if (classForName) { obj = objc_msgSend(classForName, @selector(alloc)); // if the initializer takes an argument... RMInitializerData initializerData = [classForName designatedInitializerForIdentifier:identifier]; if (initializerData.data) { // pass it. obj = objc_msgSend(obj, initializerData.designatedInitializer, initializerData.data); } else { obj = objc_msgSend(obj, initializerData.designatedInitializer); } [singletonCollection setObject:obj forKey:key]; [obj release]; } else { // raise an exception if there is no class for the specified name. NSException *exception = [NSException exceptionWithName:@"com.RMDev.RMSingletonCollector.failed_to_find_class" reason:[NSString stringWithFormat:@"SingletonCollector couldn't find class for name: %@", [className description]] userInfo:nil]; [exception raise]; [exception release]; } return obj; } + (id<RMWeakObjectReference>)referenceForObjectOfType:(NSString *)className identifier:(NSString *)identifier { id obj = [self collectionObjectForType:className identifier:identifier]; RMWeakObjectRef *objectRef = [[RMWeakObjectRef alloc] initWithObject:obj identifier:identifier]; return [objectRef autorelease]; } + (void)destroyCollection { NSDictionary *userInfo = [singletonCollection copy]; [[NSNotificationCenter defaultCenter] postNotificationName:willDestroySingletonCollection object:self userInfo:userInfo]; [userInfo release]; // release the collection and set it to nil. [self setSingletonCollection:nil]; } + (void)destroyCollectionObjectForType:(NSString *)className identifier:(NSString *)identifier { NSString *key; if (identifier) { key = [className stringByAppendingFormat:@".%@", identifier]; } else { key = className; } [[NSNotificationCenter defaultCenter] postNotificationName:willDestroySingletonCollectionObject object:[singletonCollection objectForKey:key] userInfo:nil]; [singletonCollection removeObjectForKey:key]; } @end RMWeakObjectRef.h // // RMWeakObjectRef.h // RMSingletonCollector // // Created by Rich Meade-Miller on 2/12/11. // Copyright 2011 Rich Meade-Miller. All rights reserved. // // In order to offset the performance loss from always having to search the dictionary, I made a retainable, weak object reference class. #import <Foundation/Foundation.h> @protocol RMWeakObjectReference <NSObject> @property (nonatomic, assign, readonly) id objectRef; @property (nonatomic, retain, readonly) NSString *className; @property (nonatomic, retain, readonly) NSString *objectIdentifier; @end @interface RMWeakObjectRef : NSObject <RMWeakObjectReference> { id objectRef; NSString *className; NSString *objectIdentifier; } - (RMWeakObjectRef *)initWithObject:(id)object identifier:(NSString *)identifier; - (void)objectWillBeDestroyed:(NSNotification *)notification; @end RMWeakObjectRef.m // // RMWeakObjectRef.m // RMSingletonCollector // // Created by Rich Meade-Miller on 2/12/11. // Copyright 2011 Rich Meade-Miller. All rights reserved. // #import "RMWeakObjectRef.h" #import "RMSingletonCollector.h" @implementation RMWeakObjectRef @dynamic objectRef; @synthesize className, objectIdentifier; - (RMWeakObjectRef *)initWithObject:(id)object identifier:(NSString *)identifier { if (self = [super init]) { NSString *classNameForObject = NSStringFromClass([object class]); className = classNameForObject; objectIdentifier = identifier; objectRef = object; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(objectWillBeDestroyed:) name:willDestroySingletonCollectionObject object:object]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(objectWillBeDestroyed:) name:willDestroySingletonCollection object:[RMSingletonCollector class]]; } return self; } - (id)objectRef { if (objectRef) { return objectRef; } objectRef = [RMSingletonCollector collectionObjectForType:className identifier:objectIdentifier]; return objectRef; } - (void)objectWillBeDestroyed:(NSNotification *)notification { objectRef = nil; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; [className release]; [super dealloc]; } @end

    Read the article

  • .NET SerialPort DataReceived event thread interference with main thread

    - by Kiran
    I am writing a serial communication program using the SerialPort class in C# to interact with a strip machine connected via a RS232 cable. When i send the command to the machine it responds with some bytes depending on the command. Like when i send a "\D" command, i am expecting to download the machine program data of 180 bytes as a continous string. As per the machine's manual, it suggests as a best practice to send an unreognized characters like comma (,) character to make sure the machine is initialized before sending the first command in the cycle. My serial communication code is as follows: public class SerialHelper { SerialPort commPort = null; string currentReceived = string.Empty; string receivedStr = string.Empty; private bool CommInitialized() { try { commPort = new SerialPort(); commPort.PortName = "COM1"; if (!commPort.IsOpen) commPort.Open(); commPort.BaudRate = 9600; commPort.Parity = System.IO.Ports.Parity.None; commPort.StopBits = StopBits.One; commPort.DataBits = 8; commPort.RtsEnable = true; commPort.DtrEnable = true; commPort.DataReceived += new SerialDataReceivedEventHandler(commPort_DataReceived); return true; } catch (Exception ex) { return false; } } void commPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort currentPort = (SerialPort)sender; currentReceived = currentPort.ReadExisting(); receivedStr += currentReceived; } internal int CommIO(string outString, int outLen, ref string inBuffer, int inLen) { receivedStr = string.Empty; inBuffer = string.Empty; if (CommInitialized()) { commPort.Write(outString); } System.Threading.Thread.Sleep(1500); int i = 0; while ((receivedStr.Length < inLen) && i < 10) { System.Threading.Thread.Sleep(500); i += 1; } if (!string.IsNullOrEmpty(receivedStr)) { inBuffer = receivedStr; } commPort.Close(); return inBuffer.Length; } } I am calling this code from a windows form as follows: len = SerialHelperObj.CommIO(",",1,ref inBuffer, 4) len = SerialHelperObj.CommIO(",",1,ref inBuffer, 4) If(inBuffer == "!?*O") { len = SerialHelperObj.CommIO("\D",2,ref inBuffer, 180) } A valid return value from the serial port looks like this: \D00000010000000000010 550 3250 0000256000 and so on ... I am getting some thing like this: \D00000010D,, 000 550 D,, and so on... I feel that my comm calls are getting interferred with the one when i send commands. But i am trying to make sure the result of the comma command then initiating the actual command. but the received thread is inserting the bytes from the previous communication cycle. Can any one please shed some light into this...? I lost quite some hair just trying to get this work. I am not sure where i am doing wrong

    Read the article

  • .NET Thread Pool - Unresponsive WinForms UI

    - by Goober
    Scenario I have a Windows Forms Application. Inside the main form there is a loop that iterates around 3000 times, Creating a new instance of a class on a new thread to perform some calculations. Bearing in mind that this setup uses a Thread Pool, the UI does stay responsive when there are only around 100 iterations of this loop (100 Assets to process). But as soon as this number begins to increase heavily, the UI locks up into eggtimer mode and the thus the log that is writing out to the listbox on the form becomes unreadable. Question Am I right in thinking that the best way around this is to use a Background Worker? And is the UI locking up because even though I'm using lots of different threads (for speed), the UI itself is not on its own separate thread? Suggested Implementations greatly appreciated.

    Read the article

  • C# Win Forms Thread Pool - Unresponsive UI

    - by Goober
    Scenario I have a Windows Form Application. Inside the main form there is a loop that iterates around 3000 times, Creating a new instance of a class on a new thread to perform some calculations. Baring in mind that this setup uses a Thread Pool, the UI does stay responsive when there are only around 100 iterations of this loop (100 Assets to process). But as soon as this number begins to increase heavily, the UI locks up into eggtimer mode and the thus the log that is writing out to the listbox on the form becomes unreadable. Question Am I right in thinking that the best way around this is to use a Background Worker? And is the UI locking up because even though I'm using lots of different threads (for speed), the UI itself is not on its own separate thread? Suggested Implementations greatly appreciated.

    Read the article

  • python urllib2 thread safety

    - by jldupont
    Is urllib2 thread safe? I find that using urllib2.urlopen sometimes results in the thread issuing the call to stop functioning. Yes I have used the timeout option to no avail. Is there a thread safe HTTP GET functionality I could use? NOTE: I am not interested in using Twisted to solve this problem. I have used Twisted in the past and I love it but this time I need a simpler solution. NOTE2: I also tried httplib with the same result (blocking).

    Read the article

  • ASP.NET Asynchronous Tasks - Worker Thread Not Releasing?

    - by user296752
    I am having an issue with testing asynchronous tasks in ASP.NET & IIS7. From what I have read, the worker thread should be released back into the thread pool while the I/O thread performs the async work, allowing ASP.NET to server other incoming requests. But when I simulate heavy load on the web application by making 20 simultaneous requests to a page (async.aspx) that performs long running async tasks, I am unable to browse to some other normal aspx page until the requests are just about done. Am I misunderstanding or missing something here? I am running Vista Biz x64, VS2008 + IIS7. I have the Async attribute applied to the Page directive.

    Read the article

  • C# How to kill parent thread

    - by Royson
    A parent has several child threads. If user click on stop button the parent thread should be killed with all child threads. //calls a main thread mainThread = new Thread(new ThreadStart(startWorking)); mainThread.Start(); //////////////////////////////////////////////// startWorking() { ManualResetEventInstance = new ManualResetEvent(false); ThreadPool.SetMaxThreads(m_ThreadPoolLimit, m_ThreadPoolLimit); for(int i = 0; i < list.count ; i++) { ThreadData obj_ThreadData = new ThreadData(); obj_ThreadData.name = list[i]; m_ThreadCount++; //execute WaitCallback obj_waitCallBack = new WaitCallback(startParsing); ThreadPool.QueueUserWorkItem(obj_waitCallBack, obj_ThreadData); } ManualResetEventInstance.WaitOne(); } I want to kill mainThread.

    Read the article

  • How to make a thread stay runnig in c#

    - by menachem
    Hello, I have a Windows Form Application (Form1) that allow the user to open another Forms (FormGraph). In order to open the FormGraph App I use a thread that open it. Here is the code that the thread is running: private void ThreadCreateCurvedGraph() { FormGraph myGraph = new FormGraph(); myGraph.CreateCurvedGraph(...); myGraph.Show(); } My problem is that myGraph closed right after it's open. 1) Does anyone know why this is happening and how to make myGraph stay open? 2) After the user closed myGraph, How do I terminate the thread? Many thanks!

    Read the article

  • python iterators and thread-safety

    - by Igor
    I have a class which is being operated on by two functions. One function creates a list of widgets and writes it into the class: def updateWidgets(self): widgets = self.generateWidgetList() self.widgets = widgets the other function deals with the widgets in some way: def workOnWidgets(self): for widget in self.widgets: self.workOnWidget(widget) each of these functions runs in it's own thread. the question is, what happens if the updateWidgets() thread executes while the workOnWidgets() thread is running? I am assuming that the iterator created as part of the for...in loop will keep some kind of reference to the old self.widgets object? So I will finish iterating over the old list... but I'd love to know for sure.

    Read the article

  • Can NSTask safely be used outside the main thread?

    - by neoneye
    Yesterday I read somewhere that NSTask isn't thread safe and that bothers me a lot, because I'm running a NSTask within a NSThread and is so far not experiencing any threading issues with it. My code is organized like this A: main thread -> B: worker thread -> C: worker task C: The worker task is a commandline program. B: The worker thread can start/stop the worker task and send it commands. A: The main thread can send commands to the worker thread. If NSTask is supposed to be used only within the main thread, then I'm considering moving the NSTask start/stop code to the main thread, just to prevent possible threading issues. Can NSTask be used outside the main thread? And if not then what may be the threading issues with NSTask?

    Read the article

  • C++ this as thread parameter, variables unavailable

    - by brecht
    I have three classes: class Rtss_Generator { int mv_transfersize; } class Rtss_GenSine : Rtss_Generator class Rtss_GenSineRpm : Rtss_GenSine Rtss_GenSine creates a thread in his constructer, it is started immediatly and the threadfunction is off-course declared static, waiting for an event to start calculating. the problem: all the variables that are accessed through the gen-pointer are 0, but it does not fail. Also, this-address in the constructer and the gen-pointer-address in the thread are the same, so the pointer is ok. this code is created and compile in visual studio 6.0 service pack 2003 ORIGINAL CODE no thread Rtss_GenSine::getNextData() { //[CALCULATION] //mv_transferSize is accessible and has ALWAYS value 1600 which is ok } NEW CODE Rtss_GenSine::Rtss_GenSine() { createThread(NULL, threadFunction, (LPVOID) this,0,0); } Rtss_GenSine::getNextData() { SetEvent(startCalculating); WaitForSingleObject(stoppedCalculaing, INFINITE); } DWORD Rtss_GenSine::threadFunction(LPVOID pParam) { Rtss_GenSine* gen = (Rtss_GenSine*) pParam; while(runThread) { WaitForSingleObject(startCalculating, INFINITE); ResetEvent(startCalculating) //[CALCULATION] //gen->mv_transferSize ---> it does not fail, but is always zero //all variables accessed via the gen-pointer are 0 setEvent(stoppedCalculaing) } }

    Read the article

  • Howto access thread data outside a thread

    - by Quandary
    Question: I start the MS Text-to-speech engine in a thread, in order to avoid a crash on DLL_attach. It starts fine, and the text to speech engine gets initialized, but I can't access ISpVoice outside the thread. How can I access ISpVoice outside the thread ? It's a global variable after all... #include <windows.h> #include <sapi.h> #include "XPThreads.h" ISpVoice * pVoice = NULL; unsigned long init_engine_thread(void* param) { Sleep(5000); printf("lolthread\n"); //HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); HRESULT hr = CoInitialize(NULL); if(FAILED(hr) ) { MessageBox(NULL, TEXT("Failed To Initialize"), TEXT("Error"), 0); char buffer[2000] ; sprintf(buffer, "An error occured: 0x%08X.\n", hr); FILE * pFile = fopen ( "c:\\temp\\CoInitialize_dll.txt" , "w" ); fwrite (buffer , 1 , strlen(buffer) , pFile ); fclose (pFile); } else { printf("trying to create instance.\n"); //HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **) &pVoice); //hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **) &pVoice); //HRESULT hr = CoCreateInstance(__uuidof(ISpVoice), NULL, CLSCTX_INPROC_SERVER, IID_ISpVoice, (void **) &pVoice); HRESULT hr = CoCreateInstance(__uuidof(SpVoice), NULL, CLSCTX_ALL, IID_ISpVoice, (void **) &pVoice); if( SUCCEEDED( hr ) ) { printf("Succeeded\n"); hr = pVoice->Speak(L"The text to speech engine has been successfully initialized.", 0, NULL); } else { printf("failed\n"); MessageBox(NULL, TEXT("Failed To Create COM instance"), TEXT("Error"), 0); char buffer[2000] ; sprintf(buffer, "An error occured: 0x%08X.\n", hr); FILE * pFile = fopen ( "c:\\temp\\CoCreateInstance_dll.txt" , "w" ); fwrite (buffer , 1 , strlen(buffer) , pFile ); fclose (pFile); } } if(pVoice != NULL) { pVoice->Release(); pVoice = NULL; } CoUninitialize(); return NULL; } XPThreads* ptrThread = new XPThreads(init_engine_thread); BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: //init_engine(); LoadLibrary(TEXT("ole32.dll")); ptrThread->Run(); break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; } return TRUE; }

    Read the article

  • Win32 Thread Exits Unexpectedly

    - by sahs
    Hello, I'm writing a C++ application. I realized that one of my worker threads may terminate unexpectedly. The (VS 2005) debug log says: The thread 'Win32 Thread' (0x5d98) has exited with code -858993460 (0xcccccccc). I surrounded all the worker thread code with a try/catch block. So, if the reason was an exception, I would catch it. But I can't: try{ ... Connection* conn = connectionPool->getConnection(); // unexpected exit occurs here ... } catch(exception& e) { ... } I have ten threads running concurrently, and only one of them gets crashed after some time, while the others continue running (and getting new [OCCI] connections). Is there an exception type that is not caught by "exception"? Or what do I not know about threads/exceptions? Thanks.

    Read the article

  • Minimizing Java Thread Context Switching Overhead

    - by binil
    I have a Java application running on Sun 1.6 32-bit VM/Solaris 10 (x86)/Nahelem 8-core(2 threads per core). A specific usecase in the application is to respond to some external message. In my performance test environment, when I prepare and send the response in the same thread that receives the external input, I get about 50 us advantage than when I hand off the message to a separate thread to send the response. I use a ThreadPoolExecutor with a SynchronousQueue to do the handoff. In your experience what is the acceptable delay between scheduling a task to a thread pool and it getting picked up for execution? What ideas had worked for you in the past to try improve this?

    Read the article

  • Sleep a thread until an event is attended in another thread from a different class

    - by Afro Genius
    I have an application that fires 2 threads, the 1st launches another class to do some processing which in turn launches a 3rd class to do yet more processing. The 2nd thread in the main class should wait until some event in the 3rd class completes before it performs its job. How can this be achieved? I had tried implementing a wait/notify to share a lock object between the two threads but technically this will not work as I found the hard way. Can I share a lock between classes? Note, an instance of the 3rd class is declared in the 1st class and passed as parameter to the 2nd class. Also I tried creating boolean value in 3rd class that tells when event is complete then poll 2nd thread till this value is true. This worked but is not very desirable. Also is actionListner a better approach to this problem?

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >