Search Results

Search found 45 results on 2 pages for 'usleep'.

Page 1/2 | 1 2  | Next Page >

  • implicit declaration of function usleep

    - by ant2009
    gcc (GCC) 4.6.3 c89 Hello, I am trying to use usleep. However, I keep getting the following warning: implicit declaration of function usleep I have included the unistd.h header file. The man pages mentions something about this. But I am not sure I understand by it: usleep(): Since glibc 2.12: _BSD_SOURCE || (_XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED) && !(_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700) Before glibc 2.12: _BSD_SOURCE || _XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED But not sure what I a to do with the above? Many thanks for any suggestions,

    Read the article

  • usleep() php5 uses 40% of idle CPU

    - by Marcin
    Hi guys I have a weird question, I have a cli php script which uses usleep (somtimes 1sec, sometimes 2sec, somtimes 100ms it depends) if there is some wait required, but what I have noticed its that once on usleep() it seems to use about 40% of idle CPU: Cpu(s): 5.3%us, 21.3%sy, 0.0%ni, 57.2%id, 0.0%wa, 0.0%hi, 0.0%si, 16.1%st any ideas ? cheers

    Read the article

  • Why are nanosleep() and usleep() too slow?

    - by user351990
    I have a program that generates packets to send to a receiver. I need an efficient method of introducing a small delay between the sending of each packet so as not to overrun the receiver. I've tried usleep() and nanosleep() but they seem to be too slow. I've implemented a busy wait loop and had more success, but it's not the most efficient method, I know. I'm interested in anyone's experiences in trying to do what I'm doing. Do others find usleep() and nanosleep() to function well for this type of application? Thanks, Danny Llewallyn

    Read the article

  • Simple POSIX threads question

    - by Andy
    Hi, I have this POSIX thread: void subthread(void) { while(!quit_thread) { // do something ... // don't waste cpu cycles if(!quit_thread) usleep(500); } // free resources ... // tell main thread we're done quit_thread = FALSE; } Now I want to terminate subthread() from my main thread. I've tried the following: quit_thread = TRUE; // wait until subthread() has cleaned its resources while(quit_thread); But it does not work! The while() clause does never exit although my subthread clearly sets quit_thread to FALSE after having freed its resources! If I modify my shutdown code like this: quit_thread = TRUE; // wait until subthread() has cleaned its resources while(quit_thread) usleep(10); Then everything is working fine! Could someone explain to me why the first solution does not work and why the version with usleep(10) suddenly works? I know that this is not a pretty solution. I could use semaphores/signals for this but I'd like to learn something about multithreading, so I'd like to know why my first solution doesn't work. Thanks!

    Read the article

  • pthread_join from a signal handler

    - by liv2hak
    I have a capture program which in addition do capturing data and writing it into a file also prints some statistics.The function that prints the statistics static void* report(void) { /*Print statistics*/ } is called roughly every second using an ALARM that expires every second.So The program is like void capture_program() { pthread_t report_thread while(!exit_now) { if(pthread_create(&report_thread,NULL,report,NULL)){ fprintf(stderr,"Error creating reporting thread! \n"); } /* Capturing code -------------- -------------- */ if(doreport) usleep(5); } } void *report(void *param) { while(true) { if(doreport) { doreport = 0 //access some register from hardware usleep(5) } } } The expiry of the timer sets the doreport flag.If this flag is set report() is called which clears the flag.I am using usleep to alternate between two threads in the program.This seems to work fine. I also have a signal handler to handle SIGINT (i.e CTRL+C) static void anysig(int sig) { if (sig != SIGINT) dagutil_set_signal_handler(SIG_DFL); /* Tell the main loop to exit */ exit_now = 1; return; } My question: 1) Is it safe to call pthread_join from inside the signal handler? 2) Should I use exit_now flag for the report thread as well?

    Read the article

  • Permanent mutex locking causing deadlock?

    - by Daniel
    I am having a problem with mutexes (pthread_mutex on Linux) where if a thread locks a mutex right again after unlocking it, another thread is not very successful getting a lock. I've attached test code where one mutex is created, along with two threads that in an endless loop lock the mutex, sleep for a while and unlock it again. The output I expect to see is "alive" messages from both threads, one from each (e.g. 121212121212. However what I get is that one threads gets the majority of locks (e.g. 111111222222222111111111 or just 1111111111111...). If I add a usleep(1) after the unlocking, everything works as expected. Apparently when the thread goes to SLEEP the other thread gets its lock - however this is not the way I was expecting it, as the other thread has already called pthread_mutex_lock. I suspect this is the way this is implemented, in that the actice thread has priority, however it causes certain problem in this particular testcase. Is there any way to prevent it (short of adding a deliberately large enough delay or some kind of signaling) or where is my error in understanding? #include <pthread.h> #include <stdio.h> #include <string.h> #include <sys/time.h> #include <unistd.h> pthread_mutex_t mutex; void* threadFunction(void *id) { int count=0; while(true) { pthread_mutex_lock(&mutex); usleep(50*1000); pthread_mutex_unlock(&mutex); // usleep(1); ++count; if (count % 10 == 0) { printf("Thread %d alive\n", *(int*)id); count = 0; } } return 0; } int main() { // create one mutex pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutex_init(&mutex, &attr); // create two threads pthread_t thread1; pthread_t thread2; pthread_attr_t attributes; pthread_attr_init(&attributes); int id1 = 1, id2 = 2; pthread_create(&thread1, &attributes, &threadFunction, &id1); pthread_create(&thread2, &attributes, &threadFunction, &id2); pthread_attr_destroy(&attributes); sleep(1000); return 0; }

    Read the article

  • multi-thread access MySQL error

    - by user188916
    I have written a simple multi-threaded C program to access MySQL,it works fine except when i add usleep() or sleep() function in each thread function. i created two pthreads in the main method, int main(){ mysql_library_init(0,NULL,NULL); printf("Hello world!\n"); init_pool(&p,100); pthread_t producer; pthread_t consumer_1; pthread_t consumer_2; pthread_create(&producer,NULL,produce_fun,NULL); pthread_create(&consumer_1,NULL,consume_fun,NULL); pthread_create(&consumer_2,NULL,consume_fun,NULL); mysql_library_end(); } void * produce_fun(void *arg){ pthread_detach(pthread_self()); //procedure while(1){ usleep(500000); printf("producer...\n"); produce(&p,cnt++); } pthread_exit(NULL); } void * consume_fun(void *arg){ pthread_detach(pthread_self()); MYSQL db; MYSQL *ptr_db=mysql_init(&db); mysql_real_connect(); //procedure while(1){ usleep(1000000); printf("consumer..."); int item=consume(&p); addRecord_d(ptr_db,"test",item); } mysql_thread_end(); pthread_exit(NULL); } void addRecord_d(MYSQL *ptr_db,const char *t_name,int item){ char query_buffer[100]; sprintf(query_buffer,"insert into %s values(0,%d)",t_name,item); //pthread_mutex_lock(&db_t_lock); int ret=mysql_query(ptr_db,query_buffer); if(ret){ fprintf(stderr,"%s%s\n","cannot add record to ",t_name); return; } unsigned long long update_id=mysql_insert_id(ptr_db); // pthread_mutex_unlock(&db_t_lock); printf("add record (%llu,%d) ok.",update_id,item); } the program output errors like: [Thread debugging using libthread_db enabled] [New Thread 0xb7ae3b70 (LWP 7712)] Hello world! [New Thread 0xb72d6b70 (LWP 7713)] [New Thread 0xb6ad5b70 (LWP 7714)] [New Thread 0xb62d4b70 (LWP 7715)] [Thread 0xb7ae3b70 (LWP 7712) exited] producer... producer... consumer...consumer...add record (31441,0) ok.add record (31442,1) ok.producer... producer... consumer...consumer...add record (31443,2) ok.add record (31444,3) ok.producer... producer... consumer...consumer...add record (31445,4) ok.add record (31446,5) ok.producer... producer... consumer...consumer...add record (31447,6) ok.add record (31448,7) ok.producer... Error in my_thread_global_end(): 2 threads didn't exit [Thread 0xb72d6b70 (LWP 7713) exited] [Thread 0xb6ad5b70 (LWP 7714) exited] [Thread 0xb62d4b70 (LWP 7715) exited] Program exited normally. and when i add pthread_mutex_lock in function addRecord_d,the error still exists. So what exactly the problem is?

    Read the article

  • Is there any memory leak in the normal routine of sqlite3_*()?

    - by reer
    A normal routine of sqlite3_prepare_v2() + sqlite3_step() + sqlite3_finalize() could contain leak. It sound ridiculous. But the test code seems to say it. Or I used the sqlite3_*() wrongly. Appreciate for any reply. __code________________________ include include // for usleep() include int multi_write (int j); sqlite3 *db = NULL; int main (void) { int ret = -1; ret = sqlite3_open("test.db", &db); ret = sqlite3_exec(db,"CREATE TABLE data_his (id INTEGER PRIMARY KEY, d1 CHAR(16))", NULL,NULL,NULL); usleep (100000); int j=0; while (1) { multi_write (j++); usleep (2000000); printf (" ----------- %d\n", j); } ret = sqlite3_close (db); return 0; } int multi_write (int j) { int ret = -1; char *sql_f = "INSERT OR REPLACE INTO data_his VALUES (%d, %Q)"; char *sql = NULL; sqlite3_stmt *p_stmt = NULL; ret = sqlite3_prepare_v2 (db, "BEGIN TRANSACTION", -1, &p_stmt, NULL); ret = sqlite3_step ( p_stmt ); ret = sqlite3_finalize ( p_stmt ); int i=0; for (i=0; i<100; i++) { sql = sqlite3_mprintf ( sql_f, j*100000 + i, "00000000000068FD"); ret = sqlite3_prepare_v2 (db, sql, -1, &p_stmt, NULL ); sqlite3_free ( sql ); //printf ("sqlite3_prepare_v2(): %d, %s\n", ret, sqlite3_errmsg (db)); ret = sqlite3_step ( p_stmt ); //printf ("sqlite3_step(): %d, %s\n", ret, sqlite3_errmsg (db)); ret = sqlite3_finalize ( p_stmt ); //printf ("sqlite3_finalize(): %d, %s\n\n", ret, sqlite3_errmsg (db)); } ret = sqlite3_prepare_v2 (db, "COMMIT TRANSACTION", -1, &p_stmt, NULL ); ret = sqlite3_step ( p_stmt ); ret = sqlite3_finalize ( p_stmt ); return 0; } __result________________________ And I watch the the process's run by top. At first, the memory statistics is: PID PPID USER STAT VSZ %MEM %CPU COMMAND 17731 15488 root S 1104 5% 7% ./sqlite3multiwrite When the printf() in while(1){} of main() prints the 150, the memory statistics is: PID PPID USER STAT VSZ %MEM %CPU COMMAND 17731 15488 root S 1552 5% 7% ./sqlite3multiwrite It sounds that after 150 for-cycles, the memory used by sqlite3multiwrite increase from 1104KB to 1552KB. What does it mean? memory leak or other thing?

    Read the article

  • Watch syntax help

    - by Jason
    In my Systems Programming class, there are weekly programming experiments, and I'm having trouble with the current one. The objective is to write a C program that slowly writes a string of text to a file, metered by usleep() in a 100 count for loop. The goal of the experiment is to observe the file size buffer in action via the watch command. However, I can't get it to work using watch -d ./output What syntax do I need for the watch command to see the changes made to the file size?

    Read the article

  • Help! I got a runaway PHP script. My server is down.

    - by gAMBOOKa
    I got a PHP script that is looping and will continue to do so for about another hour. How do I stop it. The script explicitly overrides the time out and the memory buffer. It's on a shared hosting server with cPanel installed. The entire website is down until the script completes. I had added a usleep(100000) statement, but it doesn't appear to work.

    Read the article

  • TCP stops sending weirdly.

    - by Utoah
    In case to find out the cause of TCP retransmits on my Linux (RHEL, kernel 2.6.18) servers connecting to the same switch. I had a client-server pair send "Hello" to each other every 200us and captured the packets with tcpdump on the client machine. The command I used to mimic client and server are: while [ 0 ]; do echo "Hello"; usleep 200; done | nc server 18510 while [ 0 ]; do echo "Hello"; usleep 200; done | nc -l 18510 When the server machine was busy serving some other requests, the client suffered from abrupt retransmits occasionally. But the output of tcpdump seemed irrational. 16:04:58.898970 IP server.18510 > client.34533: P 4531:4537(6) ack 3204 win 123 <nop,nop,timestamp 1923778643 3452833828> 16:04:58.901797 IP client.34533 > server.18510: P 3204:3210(6) ack 4537 win 33 <nop,nop,timestamp 3452833831 1923778643> 16:04:58.901855 IP server.18510 > client.34533: P 4537:4549(12) ack 3210 win 123 <nop,nop,timestamp 1923778646 3452833831> 16:04:58.903871 IP client.34533 > server.18510: P 3210:3216(6) ack 4549 win 33 <nop,nop,timestamp 3452833833 1923778646> 16:04:58.903950 IP server.18510 > client.34533: P 4549:4555(6) ack 3216 win 123 <nop,nop,timestamp 1923778648 3452833833> 16:04:58.905796 IP client.34533 > server.18510: P 3216:3222(6) ack 4555 win 33 <nop,nop,timestamp 3452833835 1923778648> 16:04:58.905860 IP server.18510 > client.34533: P 4555:4561(6) ack 3222 win 123 <nop,nop,timestamp 1923778650 3452833835> 16:04:58.908903 IP client.34533 > server.18510: P 3222:3228(6) ack 4561 win 33 <nop,nop,timestamp 3452833838 1923778650> 16:04:58.908966 IP server.18510 > client.34533: P 4561:4567(6) ack 3228 win 123 <nop,nop,timestamp 1923778653 3452833838> 16:04:58.911855 IP client.34533 > server.18510: P 3228:3234(6) ack 4567 win 33 <nop,nop,timestamp 3452833841 1923778653> 16:04:59.112573 IP client.34533 > server.18510: P 3228:3234(6) ack 4567 win 33 <nop,nop,timestamp 3452834042 1923778653> 16:04:59.112648 IP server.18510 > client.34533: P 4567:5161(594) ack 3234 win 123 <nop,nop,timestamp 1923778857 3452834042> 16:04:59.112659 IP client.34533 > server.18510: P 3234:3672(438) ack 5161 win 35 <nop,nop,timestamp 3452834042 1923778857> 16:04:59.114427 IP server.18510 > client.34533: P 5161:5167(6) ack 3672 win 126 <nop,nop,timestamp 1923778858 3452834042> 16:04:59.114439 IP client.34533 > server.18510: P 3672:3678(6) ack 5167 win 35 <nop,nop,timestamp 3452834044 1923778858> 16:04:59.116435 IP server.18510 > client.34533: P 5167:5173(6) ack 3678 win 126 <nop,nop,timestamp 1923778860 3452834044> 16:04:59.116444 IP client.34533 > server.18510: P 3678:3684(6) ack 5173 win 35 <nop,nop,timestamp 3452834046 1923778860> Packet 3228:3234(6) from client was retransmitted due to ack timeout. What I could not understand was that the client machine did not send out any packets after the first 3228:3234(6) packets was sent. The server machine had advertised a window (scaled) large enough. The data transfer up to the retransmit was fine which meant no slow start should be in action. What can cause the client machine to stop sending until the packet timed out? BTW, I am unable to run tcpdump on the server machine.

    Read the article

  • Perl kill(0, $pid) in Windows always returning 1

    - by banshee_walk_sly
    I'm trying to make a Perl script that will run a set of other programs in Windows. I need to be able to capture the stdout, stderr, and exit code of the process, and I need to be able to see if a process exceeds it's allotted execution time. Right now, the pertinent part of my code looks like: ... $pid = open3($wtr, $stdout, $stderr, $command); if($time < 0){ waitpid($pid, 0); $return = $? >> 8; $death_sig = $? & 127; $core_dump = $? & 128; } else{ # Do timeout stuff, currently not working as planned print "pid: $pid\n"; my $elapsed = 0; #THIS LOOP ONLY TERMINATES WHEN $time > $elapsed ...? while(kill 0, $pid and $time > $elapsed){ Time::HiRes::usleep(1000); # sleep for milliseconds $elapsed += 1; $return = $? >> 8; $death_sig = $? & 127; $core_dump = $? & 128; } if($elapsed >= $time){ $status = "FAIL"; print $log "TIME LIMIT EXCEEDED\n"; } } #these lines are needed to grab the stdout and stderr in arrays so # I may reuse them in multiple logs if(fileno $stdout){ @stdout = <$stdout>; } if(fileno $stderr){ @stderr = <$stderr>; } ... Everything is working correctly if $time = -1 (no timeout is needed), but the system thinks that kill 0, $pid is always 1. This makes my loop run for the entirety of the time allowed. Some extra details just for clarity: This is being run on Windows. I know my process does terminate because I have get all the expected output. Perl version: This is perl, v5.10.1 built for MSWin32-x86-multi-thread (with 2 registered patches, see perl -V for more detail) Copyright 1987-2009, Larry Wall Binary build 1007 [291969] provided by ActiveState http://www.ActiveState.com Built Jan 26 2010 23:15:11 I appreciate your help :D For that future person who may have a similar issue I got the code to work, here is the modified code sections: $pid = open3($wtr, $stdout, $stderr, $command); close($wtr); if($time < 0){ waitpid($pid, 0); } else{ print "pid: $pid\n"; my $elapsed = 0; while(waitpid($pid, WNOHANG) <= 0 and $time > $elapsed){ Time::HiRes::usleep(1000); # sleep for milliseconds $elapsed += 1; } if($elapsed >= $time){ $status = "FAIL"; print $log "TIME LIMIT EXCEEDED\n"; } } $return = $? >> 8; $death_sig = $? & 127; $core_dump = $? & 128; if(fileno $stdout){ @stdout = <$stdout>; } if(fileno $stderr){ @stderr = <$stderr>; } close($stdout); close($stderr);

    Read the article

  • Portable C++ library for IPC (processes and shared memory), Boost vs ACE vs Poco?

    - by user363778
    Hi, I need a portable C++ library for doing IPC. I used fork() and SysV shared memory until now but this limits me to Linux/Unix. I found out that there are 3 major C++ libraries that offer a portable solution (including Windows and Mac OS X). I really like Boost, and would like to use it but I need processes and it seems like that this is only an experimental branch until now!? I have never heard of ACE or POCO before and thus I am stuck I do not know which one to choose. I need fork(), sleep() (usleep() would be great) and shared memory of course. Performance and documentation are also important criteria. Thanks, for your Help!

    Read the article

  • set Image to Button

    - by Ivan
    Hello all, Could somebody help me a little bit with my issue below? When I call the myFunction, images which I want to set to buttons appear after 2 sec simultaneously, not one by one with delay of 0.5 sec. More info: generatedNumbers is array with four elements of NSNumber (4,1,3,2) buttons are set in UIView via IB and are tagged (1,2,3,4) -(IBAction) myFunction:(id) sender { int i, value; for (i = 0; i<[generatedNumbers count]; i++) { value = [[generatedNumbers objectAtIndex:i] intValue]; UIButton *button = (UIButton *)[self.view viewWithTag:i+1]; UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"%d.png",value]]; [button setImage:img forState:UIControlStateNormal]; [img release]; usleep(500000); } }

    Read the article

  • Cocoa multiple threads, locks don't work

    - by Igor
    I have a threadMethod which shows in console robotMotorsStatus every 0.5 sec. But when I try to change robotMotorsStatus in changeRobotStatus method I receive an exception. Where I need to put locks in that program. #import "AppController.h" @implementation AppController extern char *robotMotorsStatus; - (IBAction)runThread:(id)sender { [self performSelectorInBackground:@selector(threadMethod) withObject:nil]; } - (void)threadMethod { char string_to_send[]="QFF001100\r"; //String prepared to the port sending (first inintialization) string_to_send[7] = robotMotorsStatus[0]; string_to_send[8] = robotMotorsStatus[1]; while(1){ [theLock lock]; usleep(500000); NSLog (@"Robot status %s", robotMotorsStatus); [theLock unlock]; } } - (IBAction)changeRobotStatus:(id)sender { robotMotorsStatus[0]='1'; }

    Read the article

  • Cocoa multhithreads, locks don't work

    - by Igor
    I have a threadMethod which shows in console robotMotorsStatus every 0.5 sec. But when I try to change robotMotorsStatus in changeRobotStatus method I receive an exception. Where I need to put locks in that program. #import "AppController.h" @implementation AppController extern char *robotMotorsStatus; - (IBAction)runThread:(id)sender { [self performSelectorInBackground:@selector(threadMethod) withObject:nil]; } - (void)threadMethod { char string_to_send[]="QFF001100\r"; //String prepared to the port sending (first inintialization) string_to_send[7] = robotMotorsStatus[0]; string_to_send[8] = robotMotorsStatus[1]; while(1){ [theLock lock]; usleep(500000); NSLog (@"Robot status %s", robotMotorsStatus); [theLock unlock]; } } - (IBAction)changeRobotStatus:(id)sender { robotMotorsStatus[0]='1'; }

    Read the article

  • JavaScript apparently waits for each AJAX call before sending another in a loop

    - by itako
    Hello. Straight to the point: I have this javascript: for(item=1;item<5;item++) { xmlhttp=new XMLHttpRequest(); xmlhttp.open("GET",'zzz.php', true); xmlhttp.send(); } And in PHP file something like this: usleep(5);die('ok'); Now the problem is javascript seems to be waiting for each ajax call to be completed before sending another one. So the first response gets back after approx. 5 seconds, next after 10 seconds and so on. That's a very simplified version of what I do, since the real script involves using cURL in PHP and jQuery as JS lib. But the problem remains the same. Why do responses come back in 5 second intervals?

    Read the article

  • How do you play or record audio (to .WAV) on Linux in C++? [closed]

    - by Jacky Alcine
    Hello, I've been looking for a way to play and record audio on a Linux (preferably Ubuntu) system. I'm currently working on a front-end to a voice recognition toolkit that'll automate a few steps required to adapt a voice model for PocketSphinx and Julius. Suggestions of alternative means of audio input/output are welcome, as well as a fix to the bug shown below. Here is the current code I've used so far to play a .WAV file: void Engine::sayText ( const string OutputText ) { string audioUri = "temp.wav"; string requestUri = this->getRequestUri( OPENMARY_PROCESS , OutputText.c_str( ) ); int error , audioStream; pa_simple *pulseConnection; pa_sample_spec simpleSpecs; simpleSpecs.format = PA_SAMPLE_S16LE; simpleSpecs.rate = 44100; simpleSpecs.channels = 2; eprintf( E_MESSAGE , "Generating audio for '%s' from '%s'..." , OutputText.c_str( ) , requestUri.c_str( ) ); FILE* audio = this->getHttpFile( requestUri , audioUri ); fclose(audio); eprintf( E_MESSAGE , "Generated audio."); if ( ( audioStream = open( audioUri.c_str( ) , O_RDONLY ) ) < 0 ) { fprintf( stderr , __FILE__": open() failed: %s\n" , strerror( errno ) ); goto finish; } if ( dup2( audioStream , STDIN_FILENO ) < 0 ) { fprintf( stderr , __FILE__": dup2() failed: %s\n" , strerror( errno ) ); goto finish; } close( audioStream ); pulseConnection = pa_simple_new( NULL , "AudioPush" , PA_STREAM_PLAYBACK , NULL , "openMary C++" , &simpleSpecs , NULL , NULL , &error ); for (int i = 0;;i++ ) { const int bufferSize = 1024; uint8_t audioBuffer[bufferSize]; ssize_t r; eprintf( E_MESSAGE , "Buffering %d..",i); /* Read some data ... */ if ( ( r = read( STDIN_FILENO , audioBuffer , sizeof (audioBuffer ) ) ) <= 0 ) { if ( r == 0 ) /* EOF */ break; eprintf( E_ERROR , __FILE__": read() failed: %s\n" , strerror( errno ) ); if ( pulseConnection ) pa_simple_free( pulseConnection ); } /* ... and play it */ if ( pa_simple_write( pulseConnection , audioBuffer , ( size_t ) r , &error ) < 0 ) { fprintf( stderr , __FILE__": pa_simple_write() failed: %s\n" , pa_strerror( error ) ); if ( pulseConnection ) pa_simple_free( pulseConnection ); } usleep(2); } /* Make sure that every single sample was played */ if ( pa_simple_drain( pulseConnection , &error ) < 0 ) { fprintf( stderr , __FILE__": pa_simple_drain() failed: %s\n" , pa_strerror( error ) ); if ( pulseConnection ) pa_simple_free( pulseConnection ); } } NOTE: If you want the rest of the code to this file, you can download it here directly from Launchpad.

    Read the article

  • PHP Output buffer flush issue on Apache/Linux

    - by Iiro Vaahtojärvi
    Hi, I'm running into issues with the PHP output buffer flushing on my Linux web server. The output buffer is maintained correctly and all the right data is pushed to it in my code, but the usual flushing mechanisms won't flush it to the browser. I have tried everything posted here: http://php.net/manual/en/function.flush.php but no success so far. I got a small script from php.net to test it: <?php ob_start(); for($i=0;$i<70;$i++) { echo 'printing...<br />'; ob_get_flush(); flush(); usleep(300000); } ?> This should print "printing..." to the browser 70 times, one line every three seconds. This works fine on my other testing environment which is based on Windows (still using apache, XAMPP package), but on my Linux server it doesn't. It waits for the script to finish before giving anything to the browser, basically ignoring the whole flush command. If anyone has experienced this before or knows of anything that could help (be it server configuration or adjustment to code) it would be greatly appreciated!

    Read the article

  • C++ Multithreading with pthread is blocking (including sockets)

    - by Sebastian Büttner
    I am trying to implement a multi threaded application with pthread. I did implement a thread class which looks like the following and I call it later twice (or even more), but it seems to block instead of execute the threads parallel. Here is what I got until now: The Thread Class is an abstract class which has the abstract method "exec" which should contain the thread code in a derive class (I did a sample of this, named DerivedThread) Thread.hpp #ifndef THREAD_H_ #define THREAD_H_ #include <pthread.h> class Thread { public: Thread(); void start(); void join(); virtual int exec() = 0; int exit_code(); private: static void* thread_router(void* arg); void exec_thread(); pthread_t pth_; int code_; }; #endif /* THREAD_H_ */ And Thread.cpp #include <iostream> #include "Thread.hpp" /*****************************/ using namespace std; Thread::Thread(): code_(0) { cout << "[Thread] Init" << endl; } void Thread::start() { cout << "[Thread] Created Thread" << endl; pthread_create( &pth_, NULL, Thread::thread_router, reinterpret_cast<void*>(this)); } void Thread::join() { cout << "[Thread] Join Thread" << endl; pthread_join(pth_, NULL); } int Thread::exit_code() { return code_; } void Thread::exec_thread() { cout << "[Thread] Execute" << endl; code_ = exec(); } void* Thread::thread_router(void* arg) { cout << "[Thread] exec_thread function in thread" << endl; reinterpret_cast<Thread*>(arg)->exec_thread(); return NULL; } DerivedThread.hpp #include "Thread.hpp" class DerivedThread : public Thread { public: DerivedThread(); virtual ~DerivedThread(); int exec(); void Close() = 0; DerivedThread.cpp [...] #include "DerivedThread.cpp" [...] int DerivedThread::exec() { //code to be executed do { cout << "Thread executed" << endl; usleep(1000000); } while (true); //dummy, just to let it run for a while } [...] Basically, I am calling this like the here: DerivedThread *thread; cout << "Creating Thread" << endl; thread = new DerivedThread(); cout << "Created thread, starting..." << endl; thread->start(); cout << "Started thread" << endl; cout << "Creating 2nd Thread" << endl; thread = new DerivedThread(); cout << "Created 2nd thread, starting..." << endl; thread->start(); cout << "Started 2nd thread" << endl; What is working great if I am only starting one of these Threads , but if I start multiple which should run together (not synced, only parallel) . But I discovered, that the thread is created, then as it tries to execute it (via start) the problem seems to block until the thread has closed. After that the next Thread is processed. I thought that pthread would do it unblocked for me, so what did I wrong? A sample output might be: Creating Thread [Thread] Thread Init Created thread, starting... [Thread] Created thread [Thread] exec_thread function in thread [Thread] Execute Thread executed Thread executed Thread executed Thread executed Thread executed Thread executed Thread executed .... Until Thread 1 is not terminated, a Thread 2 won't be created not executed. The process above is executed in an other class. Just for the information: I am trying to create a multi threaded server. The concept is like this: MultiThreadedServer Class has a main loop, like this one: ::inet::ServerSock *sock; //just a simple self made wrapper class for sockets DerivedThread *thread; for (;;) { sock = new ::inet::ServerSock(); this->Socket->accept( *sock ); cout << "Creating Thread" << endl; //Threads (according to code sample above) thread = new DerivedThread(sock); //I did not mentoine the parameter before as it was not neccesary, in fact, I pass the socket handle with the connected socket to the thread cout << "Created thread, starting..." << endl; thread->start(); cout << "Started thread" << endl; } So I thought that this would loop over and over and wait for new connections to accept. and when a new client arrives, I am creating a new thread and give the thread the connected socket as a parameter. In the DerivedThread::exec I am doing the handling for the connected client. Like: [...] do { [...] if (this-sock_-read( Buffer, sizeof(PacketStruc) ) 0) { cout << "[Handler_Base] Recv Packet" << endl; //handle the packet } else { Connected = false; } delete Buffer; } while ( Connected ); So I loop in the created thread as long as the client keeps the connection. I think, that the socket may cause the blocking behaviour. Edit: I figured out, that it is not the read() loop in the DerivedThread Class as I simply replaced it with a loop over a simple cout-usleep part. It did also only execute the first one and after first thread finished, the 2nd one was executed. Many thanks and best regards, Sebastian

    Read the article

  • PHP jQuery Long Polling Chat Application

    - by Tejas Jadhav
    I've made a simple PHP jQuery Chat Application with Short Polling (AJAX Refresh). Like, every 2 - 3 seconds it asks for new messages. But, I read that Long Polling is a better approach for Chat applications. So, I went through some Long Polling scripts. I made like this: Javascript: $("#submit").click(function(){ $.ajax({ url: 'chat-handler.php', dataType: 'json', data: {action : 'read', message : 'message'} }); }); var getNewMessage = function() { $.ajax({ url: 'chat-handler.php', dataType: 'json', data: {action : 'read', message : 'message'}, function(data){ alert(data); } }); getNewMessage(); } $(document).ready(getNewMessage); PHP <?php $time = time(); while ((time() - $time) < 25) { $data = $db->getNewMessage (); if (!empty ($data)) { echo json_encode ($data); break; } usleep(1000000); // 1 Second } ?> The problem is, once getNewMessage() starts, it executes unless it gets some response (from chat-handler.php). It executes recursively. But if someone wants to send a message in between, then actually that function ($("#submit").click()) never executes as getNewMessage() is still executing. So is there any workaround?

    Read the article

  • Inject runtime exception to pthread sometime fails. How to fix that?

    - by lionbest
    I try to inject the exception to thread using signals, but some times the exception is not get caught. For example the following code: void _sigthrow(int sig) { throw runtime_error(strsignal(sig)); } struct sigaction sigthrow = {{&_sigthrow}}; void* thread1(void*) { sigaction(SIGINT,&sigthrow,NULL); try { while(1) usleep(1); } catch(exception &e) { cerr << "Thread1 catched " << e.what() << endl; } }; void* thread2(void*) { sigaction(SIGINT,&sigthrow,NULL); try { while(1); } catch(exception &e) { cerr << "Thread2 catched " << e.what() << endl; //never goes here } }; If I try to execute like: int main() { pthread_t p1,p2; pthread_create( &p1, NULL, &thread1, NULL ); pthread_create( &p2, NULL, &thread2, NULL ); sleep(1); pthread_kill( p1, SIGINT); pthread_kill( p2, SIGINT); sleep(1); return EXIT_SUCCESS; } I get the following output: Thread1 catched Interrupt terminate called after throwing an instance of 'std::runtime_error' what(): Interrupt Aborted How can I make second threat catch exception? Is there better idea about injecting exceptions?

    Read the article

  • Strange results while measuring delta time on Linux

    - by pachanga
    Folks, could you please explain why I'm getting very strange results from time to time using the the following code: #include <unistd.h> #include <sys/time.h> #include <time.h> #include <stdio.h> int main() { struct timeval start, end; long mtime, seconds, useconds; while(1) { gettimeofday(&start, NULL); usleep(2000); gettimeofday(&end, NULL); seconds = end.tv_sec - start.tv_sec; useconds = end.tv_usec - start.tv_usec; mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5; if(mtime > 10) printf("WTF: %ld\n", mtime); } return 0; } (You can compile and run it with: gcc test.c -o out -lrt && ./out) What I'm experiencing is sporadic big values of mtime variable almost every second or even more often, e.g: $ gcc test.c -o out -lrt && ./out WTF: 14 WTF: 11 WTF: 11 WTF: 11 WTF: 14 WTF: 13 WTF: 13 WTF: 11 WTF: 16 How can this be possible? Is it OS to blame? Does it do too much context switching? But my box is idle( load average: 0.02, 0.02, 0.3). Here is my Linux kernel version: $ uname -a Linux kurluka 2.6.31-21-generic #59-Ubuntu SMP Wed Mar 24 07:28:56 UTC 2010 i686 GNU/Linux

    Read the article

1 2  | Next Page >