Search Results

Search found 3641 results on 146 pages for 'threads'.

Page 16/146 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • Getting data from JFrame AFTER the form is filled

    - by mary jane
    I'm trying to get data for my application from a form set in an external window (getDataWindow extends javax.swing.JFrame). The problem is that functions are executed before form is filled in. getDataWindow dataW=new getDataWindow(); dataW.setVisible(true); size=dataW.returnSize(); I've tried also adding additional boolean variable to getDataWindow getDataWindow dataW=new getDataWindow(); dataW.setVisible(true); while(!dataW.checkIfReady()){wait();} size=dataW.returnSize(); But it makes also the window wait (it appears but it's black inside and nothing happens). I think i should create some threads for that - I've tried to call a window making function getDataWindow in java.awt.EventQueue.invokeLater(new Runnable()) but I had to initialize dataW earlier so dataW.checkIfReady() could be called, so it is a catch 22.

    Read the article

  • Do I need to using locking against integers in c++ threads

    - by Shane MacLaughlin
    The title says it all really. If I am accessing a single integer type (e.g. long, int, bool, etc...) in multiple threads, do I need to use a synchronisation mechanism such as a mutex to lock them. My understanding is that as atomic types, I don't need to lock access to a single thread, but I see a lot of code out there that does use locking. Profiling such code shows that there is a significant performance hit for using locks, so I'd rather not. So if the item I'm accessing corresponds to a bus width integer (e.g. 4 bytes on a 32 bit processor) do I need to lock access to it when it is being used across multiple threads? Put another way, if thread A is writing to integer variable X at the same time as thread B is reading from the same variable, is it possible that thread B could end up a few bytes of the previous value mixed in with a few bytes of the value being written? Is this architecture dependent, e.g. ok for 4 byte integers on 32 bit systems but unsafe on 8 byte integers on 64 bit systems? Edit: Just saw this related post which helps a fair bit.

    Read the article

  • New thread per client connection in socket server?

    - by Olaseni
    I am trying to optimize multiple connections per time to a TCP socket server. Is it considered good practice, or even rational to initiate a new thread in the listening server every time I receive a connection request? At what time should I begin to worry about a server based on this infrastructure? What is the maximum no of background threads I can work, until it doesn't make any sense anymore? Platform is C#, framework is Mono, target OS is CentOS, RAM is 2.4G, server is on the clouds, and I'm expecting about 200 connection requests per second.

    Read the article

  • Reading a variable messes it up?!?!

    - by EpsilonVector
    We have the following line of code: printf("%d\n", toc->runlist.next); printf("%d\n", toc->runlist.next); These are the definitions: typedef struct thread_overview_control{ int id[NR_UTHREADS]; list_t runlist; int active_counter; int main_thread; int need_resched; } thread_overview_control; thread_overview_control* toc; What I'm trying to do is implement user threads. For some reason the output of the above code at the point where our test run crushes is: 12345678 //some address 0 //NOW IT'S NULL?!?!?! How can this happen?? All we do is read a variable. And the strange thing is, without printf's there are no crashes. What's going on?

    Read the article

  • wxpython - Running threads sequentially without blocking GUI

    - by ryantmer
    I've got a GUI script with all my wxPython code in it, and a separate testSequences module that has a bunch of tasks that I run based on input from the GUI. The tasks take a long time to complete (from 20 seconds to 3 minutes), so I want to thread them, otherwise the GUI locks up while they're running. I also need them to run one after another, since they all use the same hardware. (My rationale behind threading is simply to prevent the GUI from locking up.) I'd like to have a "Running" message (with varying number of periods after it, i.e. "Running", "Running.", "Running..", etc.) so the user knows that progress is occurring, even though it isn't visible. I'd like this script to run the test sequences in separate threads, but sequentially, so that the second thread won't be created and run until the first is complete. Since this is kind of the opposite of the purpose of threads, I can't really find any information on how to do this... Any help would be greatly appreciated. Thanks in advance! gui.py import testSequences from threading import Thread #wxPython code for setting everything up here... for j in range(5): testThread = Thread(target=testSequences.test1) testThread.start() while testThread.isAlive(): #wait until the previous thread is complete time.sleep(0.5) i = (i+1) % 4 self.status.SetStatusText("Running"+'.'*i) testSequences.py import time def test1(): for i in range(10): print i time.sleep(1) (Obviously this isn't the actual test code, but the idea is the same.)

    Read the article

  • Thread toggling

    - by sid
    Hi all, In Ubuntu, I am running 2 'C' applications, When I press key up/down the applications are alternatively getting the events. What might be the problem/solution? Ex: I have 'A application' and 'B application', I launch 'A application' and press the key up/down its working fine. If I simultaneously launch 'B application' and focus is on 'B application' then pressing key up/down will toggle between 'A application' & 'B application' so 2 times I have to press the key to move on 'B application'(focus is on 'B application'). 'A application' and 'B application' are threads. Thanks in advance-opensid

    Read the article

  • Does SetThreadPriority cause thread reschedulling?

    - by Suma
    Consider following situation, assuming single CPU system: thread A is running with a priority THREAD_PRIORITY_NORMAL, signals event E thread B with a priority THREAD_PRIORITY_LOWEST is waiting for an event E (Note: at this point the thread is not scheduled because it is runnable, but A is higher priority and runnable as well) thread A calls SetThreadPriority(B, THREAD_PRIORITY_ABOVE_NORMAL) Is thread B re-scheduled immediately to run, or is thread A allowed to continue until current time-slice is over, and B is scheduled only once a new time-slice has begun? I would be interested to know the answer for WinXP, Vista and Win7, if possible. Note: the scenario above is simplified from my real world code, where multiple threads are running on multiple cores, but the main object of the question stays: does SetThreadPriority cause thread scheduling to happen?

    Read the article

  • Pass off execution to different/specific thread in Java

    - by Mike
    I have about 4 threads. One thread keeps checking some data that the other thread is updating. The others are doing some processing in the background. All have been started at this point. My question is when the checking thread sees that the data has not been updated yet I currently sleep for a little bit but is there any way for me to tell the system to back to executing the thread that does the updating? That or is there any way I can put something like a listener on the data(a String) and once its updated an event will fire that will do what it needs to do? I tried using yield() and it seemed to just keep returning to the thread I called yield() from. Thanks

    Read the article

  • Can a thread call wait() on two locks at once in Java (6)

    - by Dr. Monkey
    I've just been messing around with threads in Java to get my head around them (it seems like the best way to do so) and now understand what's going on with synchronize, wait() and notify(). I'm curious about whether there's a way to wait() on two resources at once. I think the following won't quite do what I'm thinking of: synchronized(token1) { synchronized(token2) { token1.wait(); token2.wait(); //won't run until token1 is returned System.out.println("I got both tokens back"); } } In this (very contrived) case token2 will be held until token1 is returned, then token1 will be held until token2 is returned. The goal is to release both token1 and token2, then resume when both are available (note that moving the token1.wait() outside the inner synchronized loop is not what I'm getting at). A loop checking whether both are available might be more appropriate to achieve this behaviour (would this be getting near the idea of double-check locking?), but would use up extra resources - I'm not after a definitive solution since this is just to satisfy my curiosity.

    Read the article

  • Threads to make video out of images

    - by masood
    updates: I think/ suspect the imageIO is not thread safe. shared by all threads. the read() call might use resources that are also shared. Thus it will give the performance of a single thread no matter how many threads used. ? if its correct . what is the solution (in practical code) Single request and response model at one time do not utilizes full network/internet bandwidth, thus resulting in low performance. (benchmark is of half speed utilization or even lower) This is to make a video out of an IP cam that gives a new image on each request. http://149.5.43.10:8001/snapshot.jpg It makes a delay of 3 - 8 seconds no matter what I do. Changed thread no. and thread time intervals, debugged the code by System.out.println statements to see if threads work. All seems normal. Any help? Please show some practical code. You may modify mine. This code works (javascript) with much smoother frame rate and max bandwidth usage. but the later code (java) dont. same 3 to 8 seconds gap. <!DOCTYPE html> <html> <head> <script type="text/javascript"> (function(){ var img="/*url*/"; var interval=50; var pointer=0; function showImg(image,idx) { if(idx<=pointer) return; document.body.replaceChild(image,document.getElementsByTagName("img")[0]); pointer=idx; preload(); } function preload() { var cache=null,idx=0;; for(var i=0;i<5;i++) { idx=Date.now()+interval*(i+1); cache=new Image(); cache.onload=(function(ele,idx){return function(){showImg(ele,idx);};})(cache,idx); cache.src=img+"?"+idx; } } window.onload=function(){ document.getElementsByTagName("img")[0].onload=preload; document.getElementsByTagName("img")[0].src="/*initial url*/"; }; })(); </script> </head> <body> <img /> </body> </html> and of java (with problem) : package camba; import java.applet.Applet; import java.awt.Button; import java.awt.Graphics; import java.awt.Image; import java.awt.Label; import java.awt.Panel; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import java.security.Timestamp; import java.util.Date; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.imageio.ImageIO; public class Camba extends Applet implements ActionListener{ Image img; TextField textField; Label label; Button start,stop; boolean terminate = false; long viewTime; public void init(){ label = new Label("please enter camera URL "); add(label); textField = new TextField(30); add(textField); start = new Button("Start"); add(start); start.addActionListener(this); stop = new Button("Stop"); add(stop); stop.addActionListener(this); } public void actionPerformed(ActionEvent e){ Button source = (Button)e.getSource(); if(source.getLabel() == "Start"){ for (int i = 0; i < 7; i++) { myThread(50*i); } System.out.println("start..."); } if(source.getLabel() == "Stop"){ terminate = true; System.out.println("stop..."); } } public void paint(Graphics g) { update(g); } public void update(Graphics g){ try{ viewTime = System.currentTimeMillis(); g.drawImage(img, 100, 100, this); } catch(Exception e) { e.printStackTrace(); } } public void myThread(final int sleepTime){ new Thread(new Runnable() { public void run() { while(!terminate){ try { TimeUnit.MILLISECONDS.sleep(sleepTime); } catch (InterruptedException ex) { ex.printStackTrace(); } long requestTime= 0; Image tempImage = null; try { URL pic = null; requestTime= System.currentTimeMillis(); pic = new URL(getDocumentBase(), textField.getText()); tempImage = ImageIO.read(pic); } catch(Exception e) { e.printStackTrace(); } if(requestTime >= /*last view time*/viewTime){ img = tempImage; Camba.this.repaint(); } } }}).start(); System.out.println("thread started..."); } }

    Read the article

  • Why is UITableView not reloading (even on the main thread)?

    - by radesix
    I have two programs that basically do the same thing. They read an XML feed and parse the elements. The design of both programs is to use an asynchronous NSURLConnection to get the data then to spawn a new thread to handle the parsing. As batches of 5 items are parsed it calls back to the main thread to reload the UITableView. My issue is it works fine in one program, but not the other. I know that the parsing is actually occuring on the background thread and I know that [tableView reloadData] is executing on the main thread; however, it doesn't reload the table until all parsing is complete. I'm stumped. As far as I can tell... both programs are structured exactly the same way. Here is some code from the app that isn't working correctly. - (void)startConnectionWithURL:(NSString *)feedURL feedList:(NSMutableArray *)list { self.feedList = list; // Use NSURLConnection to asynchronously download the data. This means the main thread will not be blocked - the // application will remain responsive to the user. // // IMPORTANT! The main thread of the application should never be blocked! Also, avoid synchronous network access on any thread. // NSURLRequest *feedURLRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:feedURL]]; self.bloggerFeedConnection = [[[NSURLConnection alloc] initWithRequest:feedURLRequest delegate:self] autorelease]; // Test the validity of the connection object. The most likely reason for the connection object to be nil is a malformed // URL, which is a programmatic error easily detected during development. If the URL is more dynamic, then you should // implement a more flexible validation technique, and be able to both recover from errors and communicate problems // to the user in an unobtrusive manner. NSAssert(self.bloggerFeedConnection != nil, @"Failure to create URL connection."); // Start the status bar network activity indicator. We'll turn it off when the connection finishes or experiences an error. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { self.bloggerData = [NSMutableData data]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [bloggerData appendData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { self.bloggerFeedConnection = nil; [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; // Spawn a thread to fetch the link data so that the UI is not blocked while the application parses the XML data. // // IMPORTANT! - Don't access UIKit objects on secondary threads. // [NSThread detachNewThreadSelector:@selector(parseFeedData:) toTarget:self withObject:bloggerData]; // farkData will be retained by the thread until parseFarkData: has finished executing, so we no longer need // a reference to it in the main thread. self.bloggerData = nil; } If you read this from the top down you can see when the NSURLConnection is finished I detach a new thread and call parseFeedData. - (void)parseFeedData:(NSData *)data { // You must create a autorelease pool for all secondary threads. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; self.currentParseBatch = [NSMutableArray array]; self.currentParsedCharacterData = [NSMutableString string]; self.feedList = [NSMutableArray array]; // // It's also possible to have NSXMLParser download the data, by passing it a URL, but this is not desirable // because it gives less control over the network, particularly in responding to connection errors. // NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; [parser setDelegate:self]; [parser parse]; // depending on the total number of links parsed, the last batch might not have been a "full" batch, and thus // not been part of the regular batch transfer. So, we check the count of the array and, if necessary, send it to the main thread. if ([self.currentParseBatch count] > 0) { [self performSelectorOnMainThread:@selector(addLinksToList:) withObject:self.currentParseBatch waitUntilDone:NO]; } self.currentParseBatch = nil; self.currentParsedCharacterData = nil; [parser release]; [pool release]; } In the did end element delegate I check to see that 5 items have been parsed before calling the main thread to perform the update. - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:kItemElementName]) { [self.currentParseBatch addObject:self.currentItem]; parsedItemsCounter++; if (parsedItemsCounter % kSizeOfItemBatch == 0) { [self performSelectorOnMainThread:@selector(addLinksToList:) withObject:self.currentParseBatch waitUntilDone:NO]; self.currentParseBatch = [NSMutableArray array]; } } // Stop accumulating parsed character data. We won't start again until specific elements begin. accumulatingParsedCharacterData = NO; } - (void)addLinksToList:(NSMutableArray *)links { [self.feedList addObjectsFromArray:links]; // The table needs to be reloaded to reflect the new content of the list. if (self.viewDelegate != nil && [self.viewDelegate respondsToSelector:@selector(parser:didParseBatch:)]) { [self.viewDelegate parser:self didParseBatch:links]; } } Finally, the UIViewController delegate: - (void)parser:(XMLFeedParser *)parser didParseBatch:(NSMutableArray *)parsedBatch { NSLog(@"parser:didParseBatch:"); [self.selectedBlogger.feedList addObjectsFromArray:parsedBatch]; [self.tableView reloadData]; } If I write to the log when my view controller delegate fires to reload the table and when cellForRowAtIndexPath fires as it's rebuilding the table then the log looks something like this: parser:didParseBatch: parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: parser:didParseBatch: parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: parser:didParseBatch: parser:didParseBatch: parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath Clearly, the tableView is not reloading when I tell it to every time. The log from the app that works correctly looks like this: parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath parser:didParseBatch: tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath tableView:cellForRowAtIndexPath

    Read the article

  • "Win32 exception occurred releasing IUnknown at..." error using Pylons and WMI

    - by Anders
    Hi all, Im using Pylons in combination with WMI module to do some basic system monitoring of a couple of machines, for POSIX based systems everything is simple - for Windows - not so much. Doing a request to the Pylons server to get current CPU, however it's not working well, or atleast with the WMI module. First i simply did (something) this: c = wmi.WMI() for cpu in c.Win32_Processor(): value = cpu.LoadPercentage However, that gave me an error when accessing this module via Pylons (GET http://ip:port/cpu): raise x_wmi_uninitialised_thread ("WMI returned a syntax error: you're probably running inside a thread without first calling pythoncom.CoInitialize[Ex]") x_wmi_uninitialised_thread: <x_wmi: WMI returned a syntax error: you're probably running inside a thread without first calling pythoncom.CoInitialize[Ex] (no underlying exception)> Looking at http://timgolden.me.uk/python/wmi/tutorial.html, i wrapped the code accordingly to the example under the topic "CoInitialize & CoUninitialize", which makes the code work, but it keeps throwing "Win32 exception occurred releasing IUnknown at..." And then looking at http://mail.python.org/pipermail/python-win32/2007-August/006237.html and the follow up post, trying to follow that - however pythoncom._GetInterfaceCount() is always 20. Im guessing this is someway related to Pylons spawning worker threads and crap like that, however im kinda lost here, advice would be nice. Thanks in advance, Anders

    Read the article

  • "The calling thread cannot access this object because a different thread owns it." While using Dispa

    - by Sdry
    I have an application, that I want to load additional xaml files, being resourcedictionaries controling the style of the application. Yet when trying to add a loaded ResourceDictionary to the mergeddictionaries I get an InvalidOperationException saying "The calling thread cannot access this object because a different thread owns it." at a point where I am not even using multiple threads. The application contains a usercontrol which loads the xaml file through a background worker, adding the loaded ResourceDictionaries to an Observablecollection. When I pass on a selected theme(=ResourceDictionary) to a function in the mainwindow of the application, it goes wrong. public void LoadTheme(Theme theme) {//sdry 2010-4-22 if(theme !=null){ this._dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => { MessageBox.Show("SKIN TEST: " + theme.Name); //> oke #if (SHOWDEBUGINFO) _selectedTheme = theme.Name; //>oke #endif Application.Current.Resources.MergedDictionaries.Clear(); //>oke Application.Current.Resources.MergedDictionaries.Add(theme.ResourceDictionary); //> InvalidOperationException //the theme object has a property named ResourceDictionary of type ResourceDictionary containing the loaded xaml })); } } My first reaction was to use the Disatcher.Invoke, even not knowing how I would not be on the gui thread, which doesn't solve a thing. So maybe my loaded theme belongs to a different thread ? but its originating from a property of a usercontrol, which should be the same thread. And its accesable untill trying to use the ResourceDictionary. This makes me confused, and not very aware of how to proceed, any help is appreciated.

    Read the article

  • Blackberry stopwatch implementation

    - by Michaela
    I'm trying to write a blackberry app that is basically a stopwatch, and displays lap times. First, I'm not sure I'm implementing the stopwatch functionality in the most optimal way. I have a LabelField (_myLabel) that displays the 'clock' - starting at 00:00. Then you hit the start button and every second the _myLabel field gets updated with how many seconds have past since the last update (should only ever increment by 1, but sometimes there is a delay and it will skip a number). I just can't think of a different way to do it - and I am new to GUI development and threads so I guess that's why. EDIT: Here is what calls the stopwatch: _timer = new Timer(); _timer.schedule(new MyTimerTask(), 250, 250); And here is the TimerTask: class MyTimerTask extends TimerTask { long currentTime; long startTime = System.currentTimeMillis(); public void run() { synchronized (Application.getEventLock()) { currentTime = System.currentTimeMillis(); long diff = currentTime - startTime; long min = diff / 60000; long sec = (diff % 60000) / 1000; String minStr = new Long(min).toString(); String secStr = new Long(sec).toString(); if (min < 10) minStr = "0" + minStr; if (sec < 10) secStr = "0" + secStr; _myLabel.setText(minStr + ":" + secStr); timerDisplay.deleteAll(); timerDisplay.add(_timerLabel); } } } Anyway when you stop the stopwatch it updates a historical table of lap time data. When this list gets long, the timer starts to degrade. If you try to scroll, then it gets really bad. Is there a better way to implement my stopwatch?

    Read the article

  • Thread resource sharing

    - by David
    I'm struggling with multi-threaded programming... I have an application that talks to an external device via a CAN to USB module. I've got the application talking on the CAN bus just fine, but there is a requirement for the application to transmit a "heartbeat" message every second. This sounds like a perfect time to use threads, so I created a thread that wakes up every second and sends the heartbeat. The problem I'm having is sharing the CAN bus interface. The heartbeat must only be sent when the bus is idle. How do I share the resource? Here is pseudo code showing what I have so far: TMainThread { Init: CanBusApi =new TCanBusApi; MutexMain =CreateMutex( "CanBusApiMutexName" ); HeartbeatThread =new THeartbeatThread( CanBusApi ); Execution: WaitForSingleObject( MutexMain ); CanBusApi->DoSomething(); ReleaseMutex( MutexMain ); } THeartbeatThread( CanBusApi ) { Init: MutexHeart =CreateMutex( "CanBusApiMutexName" ); Execution: Sleep( 1000 ); WaitForSingleObject( MutexHeart ); CanBusApi->DoHeartBeat(); ReleaseMutex( MutexHeart ); } The problem I'm seeing is that when DoHeartBeat is called, it causes the main thread to block while waiting for MutexMain as expected, but DoHeartBeat also stops. DoHeartBeat doesn't complete until after WaitForSingleObject(MutexMain) times out in failure. Does DoHeartBeat execute in the context of the MainThread or HeartBeatThread? It seems to be executing in MainThread. What am I doing wrong? Is there a better way? Thanks, David

    Read the article

  • Lightweight spinlocks built from GCC atomic operations?

    - by Thomas
    I'd like to minimize synchronization and write lock-free code when possible in a project of mine. When absolutely necessary I'd love to substitute light-weight spinlocks built from atomic operations for pthread and win32 mutex locks. My understanding is that these are system calls underneath and could cause a context switch (which may be unnecessary for very quick critical sections where simply spinning a few times would be preferable). The atomic operations I'm referring to are well documented here: http://gcc.gnu.org/onlinedocs/gcc-4.4.1/gcc/Atomic-Builtins.html Here is an example to illustrate what I'm talking about. Imagine a RB-tree with multiple readers and writers possible. RBTree::exists() is read-only and thread safe, RBTree::insert() would require exclusive access by a single writer (and no readers) to be safe. Some code: class IntSetTest { private: unsigned short lock; RBTree<int>* myset; public: // ... void add_number(int n) { // Aquire once locked==false (atomic) while (__sync_bool_compare_and_swap(&lock, 0, 0xffff) == false); // Perform a thread-unsafe operation on the set myset->insert(n); // Unlock (atomic) __sync_bool_compare_and_swap(&lock, 0xffff, 0); } bool check_number(int n) { // Increment once the lock is below 0xffff u16 savedlock = lock; while (savedlock == 0xffff || __sync_bool_compare_and_swap(&lock, savedlock, savedlock+1) == false) savedlock = lock; // Perform read-only operation bool exists = tree->exists(n); // Decrement savedlock = lock; while (__sync_bool_compare_and_swap(&lock, savedlock, savedlock-1) == false) savedlock = lock; return exists; } }; (lets assume it need not be exception-safe) Is this code indeed thread-safe? Are there any pros/cons to this idea? Any advice? Is the use of spinlocks like this a bad idea if the threads are not truly concurrent? Thanks in advance. ;)

    Read the article

  • Is it possible that a single-threaded program is executed simultaneously on more than one CPU core?

    - by Wolfgang Plaschg
    When I run a single-threaded program that i have written on my quad core Intel i can see in the Windows Task Manager that actually all four cores of my CPU are more or less active. One core is more active than the other three, but there is also activity on those. There's no other program (besided the OS kernel of course) running that would be plausible for that activitiy. And when I close my program all activity an all cores drops down to nearly zero. All is left is a little "noise" on the cores, so I'm pretty sure all the visible activity comes directly or indirectly (like invoking system routines) from my program. Is it possible that the OS or the cores themselves try to balance some code or execution on all four cores, even it's not a multithreaded program? Do you have any links that documents this technique? Some infos to the program: It's a console app written in Qt, the Task Manager states that only one thread is running. Maybe Qt uses threads, but I don't use signals or slots, nor any GUI. Link to Task Manager screenshot: http://img97.imageshack.us/img97/6403/taskmanager.png This question is language agnostic and not tied to Qt/C++, i just want to know if Windows or Intel do to balance also single-threaded code on all cores. If they do, how does this technique work? All I can think of is, that kernel routines like reading from disk etc. is scheduled on all cores, but this won't improve performance significantly since the code still has to run synchronous to the kernel api calls. EDIT Do you know any tools to do a better analysis of single and/or multi-threaded programs than the poor Windows Task Manager?

    Read the article

  • How to create a console application that does not terminate?

    - by John
    Hello, In C++,a console application can have a message handler in its Winmain procedure.Like this: int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { HWND hwnd; MSG msg; #ifdef _DEBUG CreateConsole("Title"); #endif hwnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, DlgProc); PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE); while(msg.message != WM_QUIT) { if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if(IsDialogMessage(hwnd, &msg)) continue; TranslateMessage(&msg); DispatchMessage(&msg); } } return 0; } This makes the process not close until the console window has received WM_QUIT message. I don't know how to do something similar in delphi. My need is not for exactly a message handler, but a lightweight "trick" to make the console application work like a GUI application using threads. So that, for example, two Indy TCP servers could be handled without the console application terminating the process. My question: How could this be accomplished?

    Read the article

  • GC output clarification

    - by elec
    I'm running a java application with the following settings: -XX:+CMSParallelRemarkEnabled -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCApplicationConcurrentTime -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps -XX:+PrintHeapAtGC -XX:+PrintTenuringDistribution I'm not sure how to interpret the related gc logs(below). In particular: Heap after GC invocations=31 (full 3): does this mean there were 31 minor GCs, and 3 full GCs ? What triggers the several consecutive lines of Total time for which the application threads were stopped and Application Time ? Is it possible to get the time stamps associated with each of these lines ? GC logs: Total time for which application threads were stopped: 0.0046910 seconds Application time: 0.7946670 seconds Total time for which application threads were stopped: 0.0002900 seconds Application time: 1.0153640 seconds Total time for which application threads were stopped: 0.0002780 seconds Application time: 1.0161890 seconds Total time for which application threads were stopped: 0.0002760 seconds Application time: 1.0145990 seconds Total time for which application threads were stopped: 0.0002950 seconds Application time: 0.9999800 seconds Total time for which application threads were stopped: 0.0002770 seconds Application time: 1.0151640 seconds Total time for which application threads were stopped: 0.0002730 seconds Application time: 0.9996590 seconds Total time for which application threads were stopped: 0.0002880 seconds Application time: 0.9624290 seconds {Heap before GC invocations=30 (full 3): par new generation total 131008K, used 130944K [0x00000000eac00000, 0x00000000f2c00000, 0x00000000f2c00000) eden space 130944K, 100% used [0x00000000eac00000, 0x00000000f2be0000, 0x00000000f2be0000) from space 64K, 0% used [0x00000000f2bf0000, 0x00000000f2bf0000, 0x00000000f2c00000) to space 64K, 0% used [0x00000000f2be0000, 0x00000000f2be0000, 0x00000000f2bf0000) concurrent mark-sweep generation total 131072K, used 48348K [0x00000000f2c00000, 0x00000000fac00000, 0x00000000fac00000) concurrent-mark-sweep perm gen total 30000K, used 19518K [0x00000000fac00000, 0x00000000fc94c000, 0x0000000100000000) 2010-05-11T09:30:13.888+0100: 384.955: [GC 384.955: [ParNew Desired survivor size 32768 bytes, new threshold 0 (max 0) : 130944K-0K(131008K), 0.0052470 secs] 179292K-48549K(262080K), 0.0053030 secs] [Times: user=0.00 sys=0.00, real=0.01 secs] Heap after GC invocations=31 (full 3): par new generation total 131008K, used 0K [0x00000000eac00000, 0x00000000f2c00000, 0x00000000f2c00000) eden space 130944K, 0% used [0x00000000eac00000, 0x00000000eac00000, 0x00000000f2be0000) from space 64K, 0% used [0x00000000f2be0000, 0x00000000f2be0000, 0x00000000f2bf0000) to space 64K, 0% used [0x00000000f2bf0000, 0x00000000f2bf0000, 0x00000000f2c00000) concurrent mark-sweep generation total 131072K, used 48549K [0x00000000f2c00000, 0x00000000fac00000, 0x00000000fac00000) concurrent-mark-sweep perm gen total 30000K, used 19518K [0x00000000fac00000, 0x00000000fc94c000, 0x0000000100000000) } Total time for which application threads were stopped: 0.0056410 seconds Application time: 0.0475220 seconds Total time for which application threads were stopped: 0.0001800 seconds Application time: 1.0174830 seconds Total time for which application threads were stopped: 0.0003820 seconds Application time: 1.0126350 seconds Total time for which application threads were stopped: 0.0002750 seconds Application time: 1.0155910 seconds Total time for which application threads were stopped: 0.0002680 seconds Application time: 1.0155580 seconds Total time for which application threads were stopped: 0.0002880 seconds Application time: 1.0155480 seconds Total time for which application threads were stopped: 0.0002970 seconds Application time: 0.9896810 seconds

    Read the article

  • Thread-safe initialization of function-local static const objects

    - by sbi
    This question made me question a practice I had been following for years. For thread-safe initialization of function-local static const objects I protect the actual construction of the object, but not the initialization of the function-local reference referring to it. Something like this: namspace { const some_type& create_const_thingy() { lock my_lock(some_mutex); static const some_type the_const_thingy; return the_const_thingy; } } void use_const_thingy() { static const some_type& the_const_thingy = create_const_thingy(); // use the_const_thingy } The idea is that locking takes time, and if the reference is overwritten by several threads, it won't matter. I'd be interested if this is safe enough in practice? safe according to The Rules? (I know, the current standard doesn't even know what "concurrency" is, but what about trampling over an already initialized reference? And do other standards, like POSIX, have something to say that's relevant to this?) For the inquiring minds: Many such function-local static const objects I used are maps which are initialized from const arrays upon first use and used for lookup. For example, I have a few XML parsers where tag name strings are mapped to enum values, so I could later switch over the tags enum values.

    Read the article

  • .Net Entity objectcontext thread error

    - by Chris Klepeis
    I have an n-layered asp.net application which returns an object from my DAL to the BAL like so: public IEnumerable<SourceKey> Get(SourceKey sk) { var query = from SourceKey in _dataContext.SourceKeys select SourceKey; if (sk.sourceKey1 != null) { query = from SourceKey in query where SourceKey.sourceKey1 == sk.sourceKey1 select SourceKey; } return query.AsEnumerable(); } This result passes through my business layer and hits the UI layer to display to the end users. I do not lazy load to prevent query execution in other layers of my application. I created another function in my DAL to delete objects: public void Delete(SourceKey sk) { try { _dataContext.DeleteObject(sk); _dataContext.SaveChanges(); } catch (Exception ex) { Debug.WriteLine(ex.Message + " " + ex.StackTrace + " " + ex.InnerException); } } When I try to call "Delete" after calling the "Get" function, I receive this error: New transaction is not allowed because there are other threads running in the session This is an ASP.Net app. My DAL contains an entity data model. The class in which I have the above functions share the same _dataContext, which is instantiated in my constructor. My guess is that the reader is still open from the "Get" function and was not closed. How can I close it?

    Read the article

  • Java - Thread problem

    - by Yatendra Goel
    My question is related to all those methods(including Thread.sleep(...)) which throw InterruptedException. I found a statement on Sun's tutorial saying InterruptedException is an exception that sleep throws when another thread interrupts the current thread while sleep is active. Is that means that the interrupt will be ignored if the sleep is not active at the time of interrupt? Suppose I have two threads: threadOne and threadTwo. threadOne creates and starts threadTwo. threadTwo executes a runnable whose run method is something like: public void run() { : : try { Thread.sleep(10 * 1000); } catch (InterruptedException e) { return; } : : : // In the middle of two sleep invocations : : try { Thread.sleep(10 * 1000); } catch (InterruptedException e) { return; } : : } After thread creation, threadOne interrupts threadTwo. Suppose the threadTwo is in the middle of two sleep invocations at the time of interrupt (when no sleep method was active), then will the second sleep method throw InterrupteException as soon as it is invoked? If not, then will this interrupt will be ignored forever? How to be sure that threadTwo will always know about the interrupt (doesn't matter whether its one of the sleep method is active or not)?

    Read the article

  • Private Java class properties mysteriously reset between method calls....

    - by Michael Jones
    I have a very odd problem. A class property is mysteriously reset between method calls. The following code is executed so the constructor is called, then the parseConfiguration method is called. Finally, processData is called. The parseConfiguration method sets the "recursive" property to "true". However, as soon as it enters "processData", "recursive" becomes "false". This problem isn't isolated to a single class -- I have several examples of this in my code. How can this possibly be happening? I've tried initialising properties when they're declared outside any methods, I've tried initialising them in constructors... nothing works. The only complication I can think of here is that this class is invoked by an object that runs in a thread -- but here is one instance per thread, so surely no chance that threads are interfering. I've tried setting both methods to "synchronized", but this still happens. Please help! /** * This class or its superclasses are NOT threaded and don't extend Thread */ public class DirectoryAcquirer extends Manipulator { /** * @var Whether to recursively scan directories */ private boolean recursive = false; /** * Constructor */ public DirectoryAcquirer() { } /** * Constructor that initialises the configuration * * @param config * @throws InvalidConfigurationException */ public DirectoryAcquirer(HierarchicalConfiguration config) throws InvalidConfigurationException { super(config); } @Override protected void parseConfiguration() throws InvalidConfigurationException { // set whether to recurse into directories or not if (this.config.containsKey("recursive")) { // this.recursive gets set to "true" here this.recursive = this.config.getBoolean("recursive"); } } @Override public EntityCollection processData(EntityCollection data) { // here this.recursive is "false" this.logger.debug("processData: Entered method"); } }

    Read the article

  • Difference in BackgroundWorker thread access in VS2010 / .NET 4.0?

    - by Jonners
    Here's an interesting one - in VS2005 / VS2008 running against .NET 2.0 / .NET 3.0 / .NET 3.5, a BackgroundWorker thread may not directly update controls on a WinForms form that initiated that thread - you'll get a System.InvalidOperationException out of the BackgroundWorker stating "Cross-thread operation not valid: Control 'thecontrol' accessed from a thread other than the thread it was created on". I remember hitting this back in 2004 or so when I first started writing .NET WinForms apps with background threads. There are several ways around the problem - this is not a question asking for that answer. I've been told recently that this kind of operation is now allowed when written in VS2010 / .NET 4.0. This seems unlikely to me, since this kind of object access restriction has always been a fairly fundamental part of thread-safe programming. Allowing a BackgroundWorker thread direct access to objects owned not by itself but by its parent UI form seems contrary to that principle. A trawl through the .NET 4.0 docs hasn't revealed any obvious changes that could account for this behaviour. I don't have VS2010 / .NET 4.0 to test this out - does anyone who has access to that toolset know for sure whether the model has changed to allow that kind of thread interaction? I'd like to either take advantage of it in future, or deploy the cluestick. ;)

    Read the article

  • rails Rake and mysql ssh port forwarding.

    - by rube_noob
    Hello, I need to create a rake task to do some active record operations via a ssh tunnel. The rake task is run on a remote windows machine so I would like to keep things in ruby. This is my latest attempt. desc "Syncronizes the tablets DB with the Server" task(:sync => :environment) do require 'rubygems' require 'net/ssh' begin Thread.abort_on_exception = true tunnel_thread = Thread.new do Thread.current[:ready] = false hostname = 'host' username = 'tunneluser' Net::SSH.start(hostname, username) do|ssh| ssh.forward.local(3333, "mysqlhost.com", 3306) Thread.current[:ready] = true puts "ready thread" ssh.loop(0) { true } end end until tunnel_thread[:ready] == true do end puts "tunnel ready" Importer.sync rescue StandardError => e puts "The Database Sync Failed." end end The task seems to hang at "tunnel ready" and never attempts the sync. I have had success when running first a rake task to create the tunnel and then running the rake sync in a different terminal. I want to combine these however so that if there is an error with the tunnel it will not attempt the sync. This is my first time using ruby Threads and Net::SSH forwarding so I am not sure what is the issue here. Any Ideas!? Thanks

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >