Search Results

Search found 2053 results on 83 pages for 'signal'.

Page 70/83 | < Previous Page | 66 67 68 69 70 71 72 73 74 75 76 77  | Next Page >

  • Memory efficient collection class

    - by Joe
    I'm building an array of dictionaries (called keys) in my iphone application to hold the section names and row counts for a tableview. the code looks like this: [self.results removeAllObjects]; [self.keys removeAllObjects]; NSUInteger i,j = 0; NSString *key = [NSString string]; NSString *prevKey = [NSString string]; if ([self.allResults count] > 0) { prevKey = [NSString stringWithString:[[[self.allResults objectAtIndex:0] valueForKey:@"name"] substringToIndex:1]]; for (NSDictionary *theDict in self.allResults) { key = [NSString stringWithString:[[theDict valueForKey:@"name"] substringToIndex:1]]; if (![key isEqualToString:prevKey]) { NSDictionary *newDictionary = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:i],@"count", prevKey,@"section", [NSNumber numberWithInt:j], @"total",nil]; [self.keys addObject:newDictionary]; prevKey = [NSString stringWithString:key]; i = 1; } else { i++; } j++; } NSDictionary *newDictionary = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:i],@"count", prevKey,@"section", [NSNumber numberWithInt:j], @"total",nil]; [self.keys addObject:newDictionary]; } [self.tableview reloadData]; The code works fine first time through but I sometimes have to rebuild the entire table so I redo this code which orks fine on the simulator, but on my device the program bombs when I execute the reloadData line : malloc: *** mmap(size=3772944384) failed (error code=12) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug malloc: *** mmap(size=3772944384) failed (error code=12) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug Program received signal: “EXC_BAD_ACCESS”. If I remove the reloadData line the code works on the device. I'm wondering if this is something to do with the way I've built the keys array (ie using autoreleased strings and dictionaries).

    Read the article

  • ncurses - resizing glitch

    - by ryyst
    I'm writing an ncurses program and am trying to make it respond correctly to terminal resizing. While I can read the terminal dimensions correctly in my program, ncurses doesn't seem to deal with new dimensions correctly. Here's a (somewhat lengthy) sample program: #include <ncurses.h> #include <string.h> #include <signal.h> #include <sys/ioctl.h> void handle_winch(int sig){ struct winsize w; ioctl(0, TIOCGWINSZ, &w); COLS = w.ws_col; LINES = w.ws_row; wresize(stdscr, LINES, COLS); clear(); mvprintw(0, 0, "COLS = %d, LINES = %d", COLS, LINES); for (int i = 0; i < COLS; i++) mvaddch(1, i, '*'); refresh(); } int main(int argc, char *argv[]){ initscr(); struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = handle_winch; sigaction(SIGWINCH, &sa, NULL); while(getch() != 27) {} endwin(); return 0; } If you run it, you can see that the terminal dimensions are correctly retrieved. But the second line, which is supposed to draw *-characters across the screen, doesn't work. Try resizing the window horizontally to make it larger, the line of *s will not get larger. What's the problem here? I'm aware that one can temporarily leave curses mode, but I'd prefer a cleaner solution. Thanks!

    Read the article

  • Using sigprocmask to implement locks

    - by EpsilonVector
    I'm implementing user threads in Linux kernel 2.4, and I'm using ualarm to invoke context switches between the threads. We have a requirement that our thread library's functions should be uninterruptable, so I looked into blocking signals and learned that using sigprocmask is the standard way to do this. However, it looks like I need to do quite a lot to implement this: sigset_t new_set, old_set; sigemptyset(&new_set); sigaddset(&new_set, SIGALRM); sigprocmask(SIG_BLOCK, &new_set, &old_set); This blocks SIGALARM but it does this with 3 function invocations! A lot can happen in the time it takes for these functions to run, including the signal being sent. The best idea I had to mitigate this was temporarily disabling ualarm, like this: sigset_t new_set, old_set; time=ualarm(0,0); sigemptyset(&new_set); sigaddset(&new_set, SIGALRM); sigprocmask(SIG_BLOCK, &new_set, &old_set); ualarm(time, 0); Which is fine except that this feels verbose. Isn't there a better way to do this?

    Read the article

  • Displaying modal view in Objective-C

    - by kpower
    I'm trying to display Modal View in my app. I have subclass of UIViewController that has only the "Done" button (UIButton created with IB and linked with XCode). .h @interface myModalVC : UIViewController { UIButton *bDone; } @property (nonatomic, retain) IBOutlet UIButton *bDone; - (IBAction)bDoneTouchDown:(id)sender; @end .m #import "myModalVC.h" @implementation myModalVC @synthesize bDone; - (void)dealloc { [bDone release]; [super dealloc]; } - (void)viewDidLoad { [super viewDidLoad]; } - (void)viewDidUnload { } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (UIInterfaceOrientationLandscapeLeft == interfaceOrientation || UIInterfaceOrientationLandscapeRight == interfaceOrientation); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } - (IBAction)bDoneTouchDown:(id)sender { [self.parentViewController dismissModalViewControllerAnimated:YES]; } @end I'm trying to display modal view with this code (from my main view): myModalVC *temp = [[[myModalVC alloc] initWithNibName:@"myModalVC" bundle:[NSBundle mainBundle]] autorelease]; [self presentModalViewController:temp animated:YES]; If this code is placed in some method, that responds to button touches - everything is fine. But when I place it to some other method (called during some processes in my app) - modal view is displayed without problems, but when I press (touch) "Done" button, application crashes with "Program received signal: “EXC_BAD_ACCESS”." What am I doing wrong?

    Read the article

  • iPhone crashing when presenting modal view controller

    - by Michael Waterfall
    I'm trying to display a modal view straight after another view has been presented modally (the second is a loading view that appears). - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; // Show load LoadViewController *loader = [[LoadViewController alloc] init]; [self presentModalViewController: loader animated:NO]; [loader release]; } But when I do this I get a "Program received signal: "EXC_BAD_ACCESS"." error. The stack trace is: 0 0x30b43234 in -[UIWindowController transitionViewDidComplete:fromView:toView:] 1 0x3095828e in -[UITransitionView notifyDidCompleteTransition:] 2 0x3091af0d in -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] 3 0x3091ad7c in -[UIViewAnimationState animationDidStop:finished:] 4 0x0051e331 in run_animation_callbacks 5 0x0051e109 in CA::timer_callback 6 0x302454a0 in CFRunLoopRunSpecific 7 0x30244628 in CFRunLoopRunInMode 8 0x32044c31 in GSEventRunModal 9 0x32044cf6 in GSEventRun 10 0x309021ee in UIApplicationMain 11 0x00002154 in main at main.m:14 Any ideas? I'm totally stumped! The loading view is empty so there's definitely nothing going on in there that's causing the error. Is it something to do with launching 2 views modally in the same event loop or something? Thanks, Mike Edit: Very strange... I have modified it slightly so that the loading view is shown after a tiny delay, and this works fine! So it appears to be something within the same event loop! - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; // Show load [self performSelector:@selector(doit) withObject:nil afterDelay:0.1]; } - (void)doit { [self presentModalViewController:loader animated:YES]; }

    Read the article

  • How to update a Widget dynamically (Not waiting 30 min for onUpdate to be called)?

    - by Donal Rafferty
    I am currently learning about widgets in Android. I want to create a WIFI widget that will display the SSID, the RSSI (Signal) level. But I also want to be able to send it data from a service I am running that calculates the Quality of Sound over wifi. Here is what I have after some reading and a quick tutorial: public class WlanWidget extends AppWidgetProvider{ RemoteViews remoteViews; AppWidgetManager appWidgetManager; ComponentName thisWidget; WifiManager wifiManager; public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Timer timer = new Timer(); timer.scheduleAtFixedRate(new WlanTimer(context, appWidgetManager), 1, 10000); } private class WlanTimer extends TimerTask{ RemoteViews remoteViews; AppWidgetManager appWidgetManager; ComponentName thisWidget; public WlanTimer(Context context, AppWidgetManager appWidgetManager) { this.appWidgetManager = appWidgetManager; remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget); thisWidget = new ComponentName(context, WlanWidget.class); wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); } @Override public void run() { remoteViews.setTextViewText(R.id.widget_textview, wifiManager.getConnectionInfo().getSSID()); appWidgetManager.updateAppWidget(thisWidget, remoteViews); } } The above seems to work ok, it updates the SSID on the widget every 10 seconds. However what is the most efficent way to get the information from my service that will be already running to update periodically on my widget? Also is there a better approach to updating the the widget rather than using a timer and timertask? (Avoid polling) UPDATE As per Karan's suggestion I have added the following code in my Service: RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget); ComponentName thisWidget = new ComponentName( context, WlanWidget.class ); remoteViews.setTextViewText(R.id.widget_QCLevel, " " + qcPercentage); AppWidgetManager.getInstance( context ).updateAppWidget( thisWidget, remoteViews ); This gets run everytime the RSSI level changes but it still never updates the TextView on my widget, any ideas why?

    Read the article

  • how to assign value to EIP with C language in ubuntu

    - by user353573
    where is wrong? how to assign value to eip to change the location of running in program? Please help !!!! error: cannot convert ‘mcontext_t*’ to ‘sigcontext*’ in assignment struct ucontext { unsigned long uc_flags; struct ucontext *uc_link; stack_t uc_stack; struct sigcontext uc_mcontext; sigset_t uc_sigmask; /* mask last for extensibility */ }; #include <stdio.h> #include <signal.h> #include <asm/ucontext.h> void handler(int signum, siginfo_t *siginfo, void *uc0){ struct ucontext *uc; struct sigcontext *sc; uc = (struct ucontext *)uc0; sc = &uc->uc_mcontext; sc->eip = target; //uc->uc_mcontext.gregs[REG_EIP] } int main (int argc, char** argv){ struct sigaction act; act.sa_sigaction = handler; act.sa_flags = SA_SIGINFO; sigaction(SIGTRAP, &act, NULL); asm("movl $skipped, %0" : : "m" (target)); asm("int3"); // cause SIGTRAP printf("to be skipped.\n"); asm("skipped:"); printf("Done.\n"); }

    Read the article

  • Syncing two AS3 NetStreams

    - by Lowgain
    I'm writing an app that requires an audio stream to be recording while a backing track is played. I have this working, but there is an inconsistent gap in between playback and record starting. I don't know if I can do anything to make the sync perfect every time, so I've been trying to track what time each stream starts so I can calculate the delay and trim it server-side. This also has proved to be a challenge as no events seem to be sent when a connection starts (as far as I know). I've tried using various properties like the streams' buffer sizes, etc. I'm thinking now that as my recorded audio is only mono, I may be able to put some kind of 'control signal' on the second stereo track which I could use to determine exactly when a sound starts recording (or stick the whole backing track in that channel so I can sync them that way). This leaves me with the new problem of properly injecting this sound into the NetStream. If anyone has any idea whether or not any of these ideas will work, how to execute them, or some alternatives, that would be extremely helpful! Been working on this issue for awhile

    Read the article

  • fix needed for bug in TextField/Text

    - by Mark
    Sort of a complicated scenario - just curious if anyone else could come up with something: I have a Text control and when I scroll it and stop the scroll with the cursor over some text that has a url, the cursor doesn't revert to a hand, and also flash player starts acting as if a selection is being made from the last cursor position. So IOW a bonafide bug in flash as far as I can determine. The above probably wasn't completely clear so let me elaborate. If you grab a scrollbar thumb and start moving it up and down, you don't actually have to keep the mouse pointer on the thumb while doing so. When you stop the scroll, the mouse pointer could be outside the browser window, inside your flash application, but not currently on the scroll bar thumb, or wherever. The previously mentioned bug occurs when you stop the scroll with the mouse pointer positioned over text with an html anchor (a hyperlink). At that point the cursor enters into some state of limbo, and doesn't show the url hand pointer, and furthermore acts as if some text selection is taking place from the last cursor position prior to the scroll. So the question would be, what sort of event could I simulate in code to jolt flash out of this erroneous state it is in. And furthermore in what event could I perform this simulated event (given that for example there is no AS3 event to signal the end of a scroll.) To be clear, the Text control in question is on a canvas, and that canvas (call it A) is on another canvas which actually owns the scrollbar, and scrolling takes place by changing the scrollRect of canvas A.

    Read the article

  • Problem when use compiled .A with simulator mode

    - by Paska
    Hi all, i have a lib .a that run only in device mode. My sdk vers is 4.2 with xcode 3.2.x. In simulator, compile correctle with no warning and no errors, but in run mode (simulator) it crash with this error: Detected an attempt to call a symbol in system libraries that is not present on the iPhone: strtod$UNIX2003 called from function pj_init in image MyAPP. If you are encountering this problem running a simulator binary within gdb, make sure you 'set start-with-shell off' first Program received signal: “SIGABRT”. I try to clean, rebuild and set "set start-with-shell off" from terminal in this way: cd ~ echo '' >> .gdbinit echo 'set start-with-shell 0' >> .gdbinit Restarted all, but nothing. The problem don't wont to resolve! Is there any tag or property that i forgotted to set in the options? In other linker flag is there only "-ObjC". It's very important to solve this issue... any idea please? thanks, A EDIT: It's my lib, compiled in simulator mode! EDIT: It run only with Simulator 4.1. Don't work with iphone 4.0, 4.2 and ipad 3.2 (all simulator).

    Read the article

  • How to properly handle signals when using the worker thread pattern?

    - by ipartola
    I have a simple server that looks something like this: void *run_thread(void *arg) { // Communicate via a blocking socket } int main() { // Initialization happens here... // Main event loop while (1) { new_client = accept(socket, ...); pthread_create(&thread, NULL, &run_thread, *thread_data*); pthread_detach(thread); } // Do cleanup stuff: close(socket); // Wait for existing threads to finish exit(0); ) Thus when a SIGINT or SIGTERM is received I need to break out of the main event loop to get to the clean up code. Moreover most likely the master thread is waiting on the accept() call so it's not able to check some other variable to see if it should break;. Most of the advice I found was along the lines of this: http://devcry.blogspot.com/2009/05/pthreads-and-unix-signals.html (creating a special signal handling thread to catch all the signals and do processing on those). However, it's the processing portion that I can't really wrap my head around: how can I possibly tell the main thread to return from the accept() call and check on an external variable to see if it should break;?

    Read the article

  • Why does using the Asynchronous Programming Model in .Net not lead to StackOverflow exceptions?

    - by uriDium
    For example, we call BeginReceive and have the callback method that BeginReceive executes when it has completed. If that callback method once again calls BeginReceive in my mind it would be very similar to recursion. How is that this does not cause a stackoverflow exception. Example code from MSDN: private static void Receive(Socket client) { try { // Create the state object. StateObject state = new StateObject(); state.workSocket = client; // Begin receiving the data from the remote device. client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); } catch (Exception e) { Console.WriteLine(e.ToString()); } } private static void ReceiveCallback( IAsyncResult ar ) { try { // Retrieve the state object and the client socket // from the asynchronous state object. StateObject state = (StateObject) ar.AsyncState; Socket client = state.workSocket; // Read data from the remote device. int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { // There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead)); // Get the rest of the data. client.BeginReceive(state.buffer,0,StateObject.BufferSize,0, new AsyncCallback(ReceiveCallback), state); } else { // All the data has arrived; put it in response. if (state.sb.Length > 1) { response = state.sb.ToString(); } // Signal that all bytes have been received. receiveDone.Set(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } }

    Read the article

  • TCP Message Structure with XML

    - by metdos
    Hello Everybody, I'm sending messages over TCP/IP and on the other side I parse TCP message.For example this is one of the sent messages. $DKMSG(requestType=REQUEST_LOGIN&requestId=123&username=metdos&password=123)$EDKMSG Clarification: $DKMSG( //Start )$EDKMSG //End requestType //Parameter REQUEST_LOGIN //Parameter Value Now I also want to add an Xml file to my message. I'm considering this option: $DKMSG(requestType=REQUEST_LOGIN&xmlData= <Item id="56D@MIT" type="SIGNAL"> <Label> <Text>56D</Text> <X1>10</X1> <Y1>40</Y1> <RotateAngle>90</RotateAngle> </Label> <X1>0</X1> <Y1>20</Y1> <Width>35</Width> <Height>10</Height> <Source>sgs3lr</Source> </Item> )$EDKMSG There are problems with this way: 1-)It doesn't seem right to me. 2-)I have to handle delimeter "=" with much more care or I need to change it in parameters. What are your suggestions, thanks.

    Read the article

  • C++ Initialize array in constructor EXC_BAD_ACCESS

    - by user890395
    I'm creating a simple constructor and initializing an array: // Construtor Cinema::Cinema(){ // Initalize reservations for(int i = 0; i < 18; i++){ for(int j = 0; j < 12; j++){ setReservation(i, j, 0); } } // Set default name setMovieName("N/A"); // Set default price setPrice(8); } The setReservation function: void Cinema::setReservation(int row, int column, int reservation){ this->reservations[row][column] = reservation; } The setMovieName function: void Cinema::setMovieName(std::string movieName){ this->movieName = movieName; } For some odd reason when I run the program, the setMovieName function gives the following error: "Program Received Signal: EXC_BAD_ACCESS" If I take out the for-loop that initializes the array of reservations, the problem goes away and the movie name is set without any problems. Any idea what I'm doing wrong? This is the Cinema.h file: #ifndef Cinema_h #define Cinema_h class Cinema{ private: int reservations[17][11]; std::string movieName; float price; public: // Construtor Cinema(); // getters/setters int getReservation(int row, int column); int getNumReservations(); std::string getMovieName(); float getPrice(); void setReservation(int row, int column, int reservation); void setMovieName(std::string movieName); void setPrice(float price); }; #endif

    Read the article

  • How much is too much memory allocation in NDK?

    - by Maximus
    The NDK download page notes that, "Typical good candidates for the NDK are self-contained, CPU-intensive operations that don't allocate much memory, such as signal processing, physics simulation, and so on." I came from a C background and was excited to try to use the NDK to operate most of my OpenGL ES functions and any native functions related to physics, animation of vertices, etc... I'm finding that I'm relying quite a bit on Native code and wondering if I may be making some mistakes. I've had no trouble with testing at this point, but I'm curious if I may run into problems in the future. For example, I have game struct defined (somewhat like is seen in the San-Angeles example). I'm loading vertex information for objects dynamically (just what is needed for an active game area) so there's quite a bit of memory allocation happening for vertices, normals, texture coordinates, indices and texture graphic data... just to name the essentials. I'm quite careful about freeing what is allocated between game areas. Would I be safer setting some caps on array sizes or should I charge bravely forward as I'm going now?

    Read the article

  • Reserve space for initially hidden widget in QVBoxLayout

    - by Skinniest Man
    I am using a QVBoxLayout to arrange a vertical stack of widgets. I want some of them to be initially hidden and only show up when a check box is checked. Here is an example of the code I'm using. MyWidget::MyWidget(QWidget *parent) : QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout(this); QLabel *labelLogTypes = new QLabel(tr("Log Types")); m_checkBoxCsv = new QCheckBox(tr("&Delimited File (CSV)")); m_labelDelimiter = new QLabel(tr("Delimiter:")); m_lineEditDelimiter = new QLineEdit(","); checkBoxCsv_Toggled(m_checkBoxCsv-isChecked()); connect(m_checkBoxCsv, SIGNAL(toggled(bool)), SLOT(checkBoxCsv_Toggled(bool))); QHBoxLayout *layoutDelimitedChar = new QHBoxLayout(); layoutDelimitedChar-addWidget(m_labelDelimiter); layoutDelimitedChar-addWidget(m_lineEditDelimiter); m_checkBoxXml = new QCheckBox(tr("&XML File")); m_checkBoxText = new QCheckBox(tr("Plain &Text File")); // Now that everything is constructed, put it all together // in the main layout. layout-addWidget(labelLogTypes); layout-addWidget(m_checkBoxCsv); layout-addLayout(layoutDelimitedChar); layout-addWidget(m_checkBoxXml); layout-addWidget(m_checkBoxText); layout-addStretch(); } MyWidget::checkBoxCsv_Toggled(bool checked) { m_labelDelimiter-setVisible(checked); m_lineEditDelimiter-setVisible(checked); } I want m_labelDelimiter and m_lineEditDelimiter both to be initially invisible and I want their visibility to toggle with the state of m_checkBoxCsv. This code acheives the functionality I desire, but it doesn't seem to reserve space for the two initially hidden widgets. When I check the checkbox, they become visible, but everything is kind of scrunched to accomodate them. If I leave them initially visible, everything is laid out just the way I would like it. Is there any way to make the QVBoxLayout reserve space for these widgets even if they're initially invisible?

    Read the article

  • are mobile can be used as a devices to develop application

    - by Richa Media and services
    I say that we can work @ mobile using a technique and work with any IDE and use any OS without problem like work on visual studio and use Window 7 How it possible ? 1. We use Mobile like a CPU and Use a monitor to watch code. We use samsung's techniques to display on monitor. it's give signal to monitor wirelessly to display code on monitor 2 We use Wireless keyboard and Mouse (if user like USB then he also use USB keyboard and mouse) 3. We use a component inside of mobile to control all devices like internet , wi-fi bluethoth. by component user easily setup , control and use feature. 4 don't be confused. i am sure to say that we not use mobile to watch code on mobile screen and Mobile 's keyboard because it's too smaller to work so we use Monitor (LCD) to display code and a keyboard to work comfortably and freely. 5. what are you think if you see a developer who work using this way 6. it is not impossible. give me some feedback and suggestion about your thinking on this technologies.

    Read the article

  • Execute a block of database querys

    - by Nightmare
    I have the following task to complete: In my program a have a block of database querys or questions. I want to execute these questions and wait for the result of all questions or catch an error if one question fails! My Question object looks like this (simplified): public class DbQuestion(String sql) { [...] } [...] //The answer is just a holder for custom data... public void SetAnswer(DbAnswer answer) { //Store the answer in the question and fire a event to the listeners this.OnAnswered(EventArgs.Empty); } [...] public void SetError() { //Signal an Error in this query! this.OnError(EventArgs.Empty); } So every question fired to the database has a listener that waits for the parsed result. Now I want to fire some questions asynchronous to the database (max. 5 or so) and fire an event with the data from all questions or an error if only one question throws one! Which is the best or a good way to accomplish this task? Can I really execute more then one question parallel and stop all my work when one question throws an error? I think I need some inspiration on this... Just a note: I´m working with .NET framework 2.0

    Read the article

  • AIX specific socket programming query

    - by kumar_m_kiran
    Hi All, Question 1 From SUSE man pages, I get the below details for socket connect options If the initiating socket is connection-mode, then connect() shall attempt to establish a connection to the address specified by the address argument. If the connection cannot be established immediately and O_NONBLOCK is not set for the file descriptor for the socket, connect() shall block for up to an unspecified timeout interval until the connection is established. If the timeout interval expires before the connection is established, connect() shall fail and the connection attempt shall be aborted. If connect() is interrupted by a signal that is caught while blocked waiting to establish a connection, connect() shall fail and set errno to [EINTR], but the connection request shall not be aborted, and the connection shall be established asynchronously. Question : Is the above contents valid for AIX OS (especially the connection time-out, timed wait ...etc)?Because I do not see it in AIX man pages (5.1 and 5.3) Question 2 I have a client socket whose attributes are a. SO_RCVTIMEO ,SO_SNDTIMEO are set for 5 seconds. b. AF_INET and SOCK_STREAM. c. SO_LINGER with linger on and time is 5 seconds. d. SO_REUSEADDR is set. Note that the client socket is not O_NONBLOCK. Question : Now since O_NONBLOCK is not set and SO_RCVTIMEO and SO_SNDTIMEO is set for 5 seconds, does it mean a. connect in NON Blocking or Blocking? b. If blocking, is it timed blocking or "infinite" time blocking? c. If it is infinite, How do I establish a "connect" system call which is O_BLOCKING with timeout to t secs. Sorry if the questions are be very naive. Thanks in advance for your input.

    Read the article

  • boost thread pool

    - by Dtag
    I need a threadpool for my application, and I'd like to rely on standard (C++11 or boost) stuff as much as possible. I realize there is an unofficial(!) boost thread pool class, which basically solves what I need, however I'd rather avoid it because it is not in the boost library itself -- why is it still not in the core library after so many years? In some posts on this page and elsewhere, people suggested using boost::asio to achieve a threadpool like behavior. At first sight, that looked like what I wanted to do, however I found out that all implementations I have seen have no means to join on the currently active tasks, which makes it useless for my application. To perform a join, they send stop signal to all the threads and subsequently join them. However, that completely nullifies the advantage of threadpools in my use case, because that makes new tasks require the creation of a new thread. What I want to do is: ThreadPool pool(4); for (...) { for (int i=0;i<something;i++) pool.pushTask(...); pool.join(); // do something with the results } Can anyone suggest a solution (except for using the existing unofficial thread pool on sourceforge)? Is there anything in C++11 or core boost that can help me here? Thanks a lot

    Read the article

  • In ArrayBlockingQueue, why copy into ReentrantLock field into local final variable?

    - by mjlee
    In ArrayBlockingQueue, any method that requires lock will get set 'final' local variable before calling 'lock()'. public boolean offer(E e) { if (e == null) throw new NullPointerException(); final ReentrantLock lock = this.lock; lock.lock(); try { if (count == items.length) return false; else { insert(e); return true; } } finally { lock.unlock(); } } Is there any reason to set a local variable 'lock' from 'this.lock' when field 'this.lock' is final also. Additionally, it also set local variable of E[] before acting on. private E extract() { final E[] items = this.items; E x = items[takeIndex]; items[takeIndex] = null; takeIndex = inc(takeIndex); --count; notFull.signal(); return x; } Is there any reason for copying to local final variable?

    Read the article

  • Creating a network adapter - how hard is it?

    - by Vilx-
    I'm interested in building a little (commercial) device on top of Arduino. I want it to be able to interface with network. Network as in standard Ethernet, Cat5, RJ-45, etc. I know that there is an Ethernet Shield, but it costs even more than the Arduino itself, and it's pretty big. Naturally, I want my device to be as small and as cheap as possible. So I'm thinking about recreating an Ethernet module myself. The problem is - I haven't got any experience with Ethernet, nor do I have a good idea where to start looking. Thus I can't even say if my ideas are feasible. Ultimately I would like the device to have three ports - one for incoming signal, two for outgoing, so the device is essentially a little switch where it is plugged in itself as well. The switching capabilities need not be very fast - the volume of data will be low. 10Mbit is more than enough, can be even slower. If that is not possible, a single port for controlling the device itself will also do. Another possibility I'm considering is power line communications - sending information through power lines. That's another area I've no experience with. What hardware should I be looking at, and where can I find information about the necessary software? So - can anyone tell me if these ideas are feasible, and if yes - where should I start looking?

    Read the article

  • Any techniques to interrupt, kill, or otherwise unwind (releasing synchronization locks) a single de

    - by gojomo
    I have a long-running process where, due to a bug, a trivial/expendable thread is deadlocked with a thread which I would like to continue, so that it can perform some final reporting that would be hard to reproduce in another way. Of course, fixing the bug for future runs is the proper ultimate resolution. Of course, any such forced interrupt/kill/stop of any thread is inherently unsafe and likely to cause other unpredictable inconsistencies. (I'm familiar with all the standard warnings and the reasons for them.) But still, since the only alternative is to kill the JVM process and go through a more lengthy procedure which would result in a less-complete final report, messy/deprecated/dangerous/risky/one-time techniques are exactly what I'd like to try. The JVM is Sun's 1.6.0_16 64-bit on Ubuntu, and the expendable thread is waiting-to-lock an object monitor. Can an OS signal directed to an exact thread create an InterruptedException in the expendable thread? Could attaching with gdb, and directly tampering with JVM data or calling JVM procedures allow a forced-release of the object monitor held by the expendable thread? Would a Thread.interrupt() from another thread generate a InterruptedException from the waiting-to-lock frame? (With some effort, I can inject an arbitrary beanshell script into the running system.) Can the deprecated Thread.stop() be sent via JMX or any other remote-injection method? Any ideas appreciated, the more 'dangerous', the better! And, if your suggestion has worked in personal experience in a similar situation, the best!

    Read the article

  • Is it safe to use a boolean flag to stop a thread from running in C#

    - by Lirik
    My main concern is with the boolean flag... is it safe to use it without any synchronization? I've read in several places that it's atomic. class MyTask { private ManualResetEvent startSignal; private CountDownLatch latch; private bool running; MyTask(CountDownLatch latch) { running = false; this.latch = latch; startSignal = new ManualResetEvent(false); } // A method which runs in a thread public void Run() { startSignal.WaitOne(); while(running) { startSignal.WaitOne(); //... some code } latch.Signal(); } public void Stop() { running = false; startSignal.Set(); } public void Start() { running = true; startSignal.Set(); } public void Pause() { startSignal.Reset(); } public void Resume() { startSignal.Set(); } } Is this a safe way to design a task? Any suggestions, improvements, comments? Note: I wrote my custom CountDownLatch class in case you're wondering where I'm getting it from.

    Read the article

  • What kind of data do I pass into a Django Model.save() method?

    - by poswald
    Lets say that we are getting POSTed a form like this in Django: rate=10 items= [23,12,31,52,83,34] The items are primary keys of an Item model. I have a bunch of business logic that will run and create more items based on this data, the results of some db lookups, and some business logic. I want to put that logic into a save signal or an overridden Model.save() method of another model (let's call it Inventory). The business logic will run when I create a new Inventory object using this form data. Inventory will look like this: class Inventory(models.Model): picked_items = models.ManyToManyField(Item, related_name="items_picked_set") calculated_items = models.ManyToManyField(Item, related_name="items_calculated_set") rate = models.DecimalField() ... other fields here ... New calculated_items will be created based on the passed in items which will be stored as picked_items. My question is this: is it better for the save() method on this model to accept: the request object (I don't really like this coupling) the form data as arguments or kwargs (a list of primary keys and the other form fields) a list of Items (The caller form or view will lookup the list of Items and create a list as well as pass in the other form fields) some other approach? I know this is a bit subjective, but I was wondering what the general idea is. I've looked through a lot of code but I'm having a hard time finding a pattern I like.

    Read the article

< Previous Page | 66 67 68 69 70 71 72 73 74 75 76 77  | Next Page >