Search Results

Search found 1096 results on 44 pages for 'never quit'.

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

  • How to stop debugging (or detach process) without stopping the process?

    - by Valentein
    I often use VS 2008 to debug a .NET C# component of an application. Sometimes, I want to quit debugging and continue running the application. Stop Debugging kills the process I was debugging. How can I achieve my aim? This is not a web app, it's a local process that runs managed and unmanaged code. I don't see any "Detach" or "Detach All" option in the Debug menu (is it enabled in some option?).

    Read the article

  • Apache authentication: Redirect on failure, reliably?

    - by bukzor
    I've set my ErrorDocument 401 to point to my website's account creation page, but not all browsers seem to honor this redirect (Safari). Also, other browsers (Firefox, Chrome) never quit asking for the password and show the ErrorDocument. This causes a good number of users to give up trying after many password attempts without seeing the account creation page. Is there any way to make the redirect more reliable, without trashing basic authentication altogether?

    Read the article

  • Is there a way to get a mobile Safari WebApp to "forget" its state?

    - by Alex Mcp
    I have a nascent bridge scoring app that is meant to be stored locally on an iPod touch/iPhone (iPad? Would probably be fugly...) So far so good, got a custom icon rolling and basic JS navigation laid out, but my problem is that it retains its state when I quit the app. Is there a simple magic Apple meta tag for this? Or is it achieved with javascript? Thanks for any insight.

    Read the article

  • Silverlight Out of Browser (OOB) app crashing only on OS X

    - by BarrettJ
    We have a Silverlight application that runs OOB (out of browser) so the user can install it. When it's running OOB we display a button that calls Application.Current.MainWindow.Close() so that the user can exit the application. This works perfectly fine on windows, but causes an error saying the application has quit unexpectedly on OS X. Anyone have any ideas why this might be? Thanks!

    Read the article

  • Swing on OSX: How to Trap command-Q?

    - by yar
    After being convinced ("schooled") that Swing apps on Mac do look native, I'm trying to make mine look as native as possible. Everything looks great, but when I hit command-Q or do it from the menu, my windowStateChanged(WindowEvent e) is not firing on my main JFrame (if I exit in any other way, it does fire). How can I respond to the real Apple quit?

    Read the article

  • Simple SELECT query problem...

    - by Povylas
    Hi, I have this MySql select query witch seams to have a bug but I am quit "green" so I simple can not see, so maybe you could help? Here is the query: SELECT node_id FROM rate WHERE node_id='".$cat_node_id_string."' LIMIT ".$node_count_star.",".$node_count_end." ORDER BY SUM(amount) GROUP BY node_id Thanks for help in advance...

    Read the article

  • RegExp to validate a formula (string/boolean/numeric expression)?

    - by JSteve
    I have used regExp quit a bit of times but still far from being an expert. This time I want to validate a formula (or math expression) by regExp. The difficult part here is to validate proper starting and ending parentheses with in the formula. I believe, there would be some sample on the web but I could not find it. Can somebody post a link for such example? or help me by some other means?

    Read the article

  • Python process will not exit

    - by oneself
    Hi, I'm use nosetests to run some tests. However, after the tests have finished running, the nosetests process just sits there, and will not exit. Is there anyway to diagnose this? Does Python have a facility similar to sending Java a kill -QUIT which will print a stack trace?

    Read the article

  • A PDF viewer with a toolbar actions

    - by amirouche
    A want a Drupal who let me to the Adminintrator upload a pdf files and the users can read them in a viewer with a Toolbar that contains print, download and quit boutons like the link text website. The possibility to have statistics on user's Toolbar actions will be appreciated.

    Read the article

  • Sending POST Requests without waiting for response?

    - by Gotys
    I am writing a simple REST service, which responds to requests from clients. All in PHP. My concern is, that when my server responds to a request, it could end up tying up resources if the client side is too slow in sending back "ok" response. How do I send a POST request via lib_curl setting it to not wait for any responses, but rather quit immidiately after the POST data have been sent? Is this even possible? Thank you !

    Read the article

  • Android. How do I keep a button displayed as PRESSED until the action created by that button is finished?

    - by user527405
    I have button_focused, button_pressed, and button_normal images. When I press the button, the button_pressed image is displayed and the action related to the button pressing begins. When I quit pressing the button, the action continues but the button returns to button_normal image being displayed. How can I set the button image being displayed to button_pressed during the entire action then reset to the button_normal image? Thank you for your time

    Read the article

  • Is it safe to read global data from multiple threads?

    - by user362515
    The scenario is as follows: Create an instance of a class (std::map) and sore it as global variable. Spawn threads. Threads read and use the same global instance of the class All spawned threads quit Global class instance is destroyed No mutex, no thread modifies the global class instance. Is this OK? Thank You

    Read the article

  • stringindexoutofbounds with currency converter java program

    - by user1795926
    I am have trouble with a summary not showing up. I am supposed to modify a previous Java assignment by by adding an array of objects. Within the loop, instantiate each individual object. Make sure the user cannot keep adding another Foreign conversion beyond your array size. After the user selects quit from the menu, prompt if the user want to display a summary report. If they select ‘Y’ then, using your array of objects, display the following report: Item Conversion Dollars Amount 1 Japanese Yen 100.00 32,000.00 2 Mexican Peso 400.00 56,000.00 3 Canadian Dollar 100.00 156.00 etc. Number of Conversions = 3 There are no errors when I compile..but when I run the program it is fine until I hit 0 to end the conversion and have it ask if i want to see a summary. This error displays: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(String.java:658) at Lab8.main(Lab8.java:43) my code: import java.util.Scanner; import java.text.DecimalFormat; public class Lab8 { public static void main(String[] args) { final int Max = 10; String a; char summary; int c = 0; Foreign[] Exchange = new Foreign[Max]; Scanner Keyboard = new Scanner(System.in); Foreign.opening(); do { Exchange[c] = new Foreign(); Exchange[c].getchoice(); Exchange[c].dollars(); Exchange[c].amount(); Exchange[c].vertical(); System.out.println("\n" + Exchange[c]); c++; System.out.println("\n" + "Please select 1 through 4, or 0 to quit" + >"\n"); c= Keyboard.nextInt(); } while (c != 0); System.out.print("\nWould you like a summary of your conversions? (Y/N): "); a = Keyboard.nextLine(); summary = a.charAt(0); summary = Character.toUpperCase(summary); if (summary == 'Y') { System.out.println("\nCountry\t\tRate\t\tDollars\t\tAmount"); System.out.println("========\t\t=======\t\t=======\t\t========="); for (int i=0; i < Exchange.length; i++) System.out.println(Exchange[i]); Foreign.counter(); } } } I looked at line 43 and its this line: summary = a.charAt(0); But I am not sure what's wrong with it, can anyone point it out? Thank you.

    Read the article

  • Is it save to read global data from multiple threads?

    - by user362515
    The scenario is as follows: Create an instance of a class (std::map) and sore it as global variable. Spawn threads. Threads read and use the same global instance of the class All spawned threads quit Global class instance is destroyed No mutex, no thread modifies the global class instance. Is it ok? Thank You

    Read the article

  • sendmail can not relay from itself

    - by Bernie
    I am running 3 centos 5.2 servers and I have configured the server for forward all messages to root to be emailed to me via .forward rule. This is working fine on two of the servers but not on the third. I have also tried copying the mail config files from the backup server and placing them on the file server and restarting sendmail. I also removed and reinstalled sendmail via yum but the results are the same. I am not sure what the issue could be they are all standard centos installs. Here is an example from the backup server which is working and the fileserver which isn't I am also going to include the mail log. good from backup server [root@backup ]# sendmail -v [email protected] < test.mail [email protected]... Connecting to [127.0.0.1] via relay... 220 backup.localhost ESMTP Sendmail 8.13.8/8.13.8; Fri, 16 Oct 2009 10:23:50 -0700 >>> EHLO backup.localhost 250-backup.localhost Hello backup.localhost [127.0.0.1], pleased to meet you 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-8BITMIME 250-SIZE 250-DSN 250-ETRN 250-DELIVERBY 250 HELP >>> MAIL From:<[email protected]> SIZE=73 250 2.1.0 <[email protected]>... Sender ok >>> RCPT To:<[email protected]> >>> DATA 250 2.1.5 <[email protected]>... Recipient ok 354 Enter mail, end with "." on a line by itself >>> . 250 2.0.0 n9GHNoGC020924 Message accepted for delivery [email protected]... Sent (n9GHNoGC020924 Message accepted for delivery) Closing connection to [127.0.0.1] >>> QUIT 221 2.0.0 backup.localhost closing connection bad from file server [root@fileserver bernie]# sendmail -v [email protected] < test.mail [email protected]... Connecting to [127.0.0.1] via relay... 220 fileserver.localhost ESMTP Sendmail 8.13.8/8.13.8; Fri, 16 Oct 2009 10:23:26 -0700 >>> EHLO fileserver.localhost 250-fileserver.localhost Hello fileserver.localhost [127.0.0.1], pleased to meet you 250 ENHANCEDSTATUSCODES >>> MAIL From:<[email protected]> 550 5.0.0 Access denied root... Using cached ESMTP connection to [127.0.0.1] via relay... >>> RSET 250 2.0.0 Reset state >>> MAIL From:<> 550 5.0.0 Access denied postmaster... Using cached ESMTP connection to [127.0.0.1] via relay... >>> RSET 250 2.0.0 Reset state >>> MAIL From:<> 550 5.0.0 Access denied Closing connection to [127.0.0.1] >>> QUIT 221 2.0.0 fileserver.localhost closing connection mail log Oct 16 10:39:13 fileserver sendmail[28059]: n9GHdDom028059: from=root, size=72, class=0, nrcpts=1, msgid=<[email protected]>, relay=root@localhost Oct 16 10:39:13 fileserver sendmail[28060]: n9GHdDwl028060: tcpwrappers (fileserver.localhost, 127.0.0.1) rejection Oct 16 10:39:13 fileserver sendmail[28059]: n9GHdDom028059: [email protected], ctladdr=root (0/0), delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=30072, relay=[127.0.0.1] [127.0.0.1], dsn=5.0.0, stat=Service unavailable Oct 16 10:39:13 fileserver sendmail[28059]: n9GHdDom028059: n9GHdDon028059: DSN: Service unavailable Oct 16 10:39:13 fileserver sendmail[28059]: n9GHdDon028059: to=root, delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=31096, relay=[127.0.0.1], dsn=5.0.0, stat=Service unavailable Oct 16 10:39:13 fileserver sendmail[28059]: n9GHdDon028059: n9GHdDoo028059: return to sender: Service unavailable Oct 16 10:39:13 fileserver sendmail[28059]: n9GHdDoo028059: to=postmaster, delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=32120, relay=[127.0.0.1], dsn=5.0.0, stat=Service unavailable Oct 16 10:39:13 fileserver sendmail[28059]: n9GHdDon028059: Losing ./qfn9GHdDon028059: savemail panic Oct 16 10:39:13 fileserver sendmail[28059]: n9GHdDon028059: SYSERR(root): savemail: cannot save rejected email anywhere

    Read the article

  • Process not Listed by PS or in /proc/

    - by Hammer Bro.
    I'm trying to figure out how to operate a rather large Java program, 'prog'. If I go to its /bin/ dir and configure its setenv.sh and prog.sh to use local directories and my current user account. Then I try to run it via "./prog.sh start". Here are all the relevant bits of prog.sh: USER=(my current account) _CMD="/opt/jdk/bin/java -server -Xmx768m -classpath "${CLASSPATH}" -jar "${DIR}/prog.jar"" case "${ACTION}" in start) nohup su ${USER} -c "exec ${_CMD} >>${_LOGFILE} 2>&1" >/dev/null & echo $! >${_PID} echo "Prog running. PID="`cat ${_PID}` ;; stop) PID=`cat ${_PID} 2>/dev/null` echo "Shutting down prog: ${PID} kill -QUIT ${PID} 2>/dev/null kill ${PID} 2>/dev/null kill -KILL ${PID} 2>/dev/null rm -f ${_PID} echo "STOPPED `date`" >>${_LOGFILE} ;; When I actually do ./prog.sh start, it starts. But I can't find it at all on the process list. Nor can I kill it manually, using the same command the shell script uses. But I can tell it's running, because if I do ./prog.sh stop, it stops (and some temporary files elsewhere clean themselves out). ./prog.sh start Prog running. PID=1234 ps eaux | grep 1234 ps eaux | grep -i prog.jar ps eaux >> pslist.txt (It's not there either by PID or any clear name I can find: prog, java or jar.) cd /proc/1234/ -bash: cd: /proc/1234/: No such file or directory kill -QUIT 1234 kill 1234 kill -KILL 1234 -bash: kill: (1234) - No such process ./prog.sh stop Shutting down prog: 1234 As far as I can tell, the process is running yet not in any way listed by the system. I can't find it in ps or /proc/, nor can I kill it. But the shell script can still stop it properly. So my question is, how can something like this happen? Is the process supremely hidden, actually unlisted, or am I just missing it in some fashion? I'm trying to figure out what makes this program tick, and I can barely prove that it's ticking! Edit: ps eu | grep prog.sh (after having restarted; so random PID) 50038 19381 0.0 0.0 4412 632 pts/3 S+ 16:09 0:00 grep prog.sh HOSTNAME=machine.server.com TERM=vt100 SHELL=/bin/bash HISTSIZE=1000 SSH_CLIENT=::[STUFF] 1754 22 CVSROOT=:[DIR] SSH_TTY=/dev/pts/3 ANT_HOME=/opt/apache-ant-1.7.1 USER=[USER] LS_COLORS=[COLORS] SSH_AUTH_SOCK=[DIR] KDEDIR=/usr MAIL=[DIR] PATH=[DIRS] INPUTRC=/etc/inputrc PWD=[PWD] JAVA_HOME=/opt/jdk1.6.0_21 LANG=en_US.UTF-8 SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass M2_HOME=/opt/apache-maven-2.2.1 SHLVL=1 HOME=[~] LOGNAME=[USER] SSH_CONNECTION=::[STUFF] LESSOPEN=|/usr/bin/lesspipe.sh %s G_BROKEN_FILENAMES=1 _=/bin/grep OLDPWD=[DIR] I just realized that the stop) part of prog.sh isn't actually a guarantee that the process it claims to be stopping is running -- it just tries to kill the PID and suppresses all output then deletes the temporary file and manually inserts STOPPED into the log file. So I'm no longer so certain that the process is always running when I ps for it, although the code sample above indicates that it at least runs erratically. I'll continue looking into this undocumented behemoth when I return to work tomorrow.

    Read the article

  • Mac Terminal.app: Force '^C' to be printed when editing current prompt, then aborting it

    - by Stefan Lasiewski
    This is the opposite of Prevent “^C” from being printed when aborting editing current prompt. I'm using Bash. When I'm editing the commandline in Bash, and I hit Control-C to abort the commandline, the '^C' character does not display. I would like to see this character. I tried commands like stty -ctlecho and stty ctlecho (which I borrowed from the other question), but this didn't work for me. This behavior seems to be true with my environment on Ubuntu, CentOS and MacOSX. This only happens within Apple's Terminal.App. If I SSH to a remote Linux or FreeBSD box, then ^C is printed. So, this is clearly just a local setting. Update: Here is the output of stty -a, as requested by @quack quixote : $ stty -a speed 9600 baud; 41 rows; 88 columns; lflags: icanon isig iexten echo echoe -echok echoke -echonl echoctl -echoprt -altwerase -noflsh -tostop -flusho pendin -nokerninfo -extproc iflags: -istrip icrnl -inlcr -igncr ixon -ixoff ixany imaxbel iutf8 -ignbrk brkint -inpck -ignpar -parmrk oflags: opost onlcr -oxtabs -onocr -onlret cflags: cread cs8 -parenb -parodd hupcl -clocal -cstopb -crtscts -dsrflow -dtrflow -mdmbuf cchars: discard = ^O; dsusp = ^Y; eof = ^D; eol = <undef>; eol2 = <undef>; erase = ^?; intr = ^C; kill = ^U; lnext = ^V; min = 1; quit = ^\; reprint = ^R; start = ^Q; status = ^T; stop = ^S; susp = ^Z; time = 0; werase = ^W; After typing stty sane, stty -a will output the following. The only difference is the parameter of -iutf8. $ stty sane $ stty -a speed 9600 baud; 41 rows; 157 columns; lflags: icanon isig iexten echo echoe -echok echoke -echonl echoctl -echoprt -altwerase -noflsh -tostop -flusho pendin -nokerninfo -extproc iflags: -istrip icrnl -inlcr -igncr ixon -ixoff ixany imaxbel -iutf8 -ignbrk brkint -inpck -ignpar -parmrk oflags: opost onlcr -oxtabs -onocr -onlret cflags: cread cs8 -parenb -parodd hupcl -clocal -cstopb -crtscts -dsrflow -dtrflow -mdmbuf cchars: discard = ^O; dsusp = ^Y; eof = ^D; eol = <undef>; eol2 = <undef>; erase = ^?; intr = ^C; kill = ^U; lnext = ^V; min = 1; quit = ^\; reprint = ^R; start = ^Q; status = ^T; stop = ^S; susp = ^Z; time = 0; werase = ^W;

    Read the article

  • The DOS DEBUG Environment

    - by MarkPearl
    Today I thought I would go back in time and have a look at the DEBUG command that has been available since the beginning of dawn in DOS, MS-DOS and Microsoft Windows. up to today I always knew it was there, but had no clue on how to use it so for those that are interested this might be a great geek party trick to pull out when you want the awe the younger generation and want to show them what “real” programming is about. But wait, you will have to do it relatively quickly as it seems like DEBUG was finally dumped from the Windows group in Windows 7. Not to worry, pull out that Windows XP box which will get you even more geek points and you can still poke DEBUG a bit. So, for those that are interested and want to find out a bit about the history of DEBUG read the wiki link here. That all put aside, lets get our hands dirty.. How to Start DEBUG in Windows Make sure your version of Windows supports DEBUG. Open up a console window Make a directory where you want to play with debug – in my instance I called it C221 Enter the directory and type Debug You will get a response with a – as illustrated in the image below…   The commands available in DEBUG There are several commands available in DEBUG. The most common ones are A (Assemble) R (Register) T (Trace) G (Go) D (Dump or Display) U (Unassemble) E (Enter) P (Proceed) N (Name) L (Load) W (Write) H (Hexadecimal) I (Input) O (Output) Q (Quit) I am not going to cover all these commands, but what I will do is go through a few of them briefly. A is for Assemble Command (to write code) The A command translates assembly language statements into machine code. It is quite useful for writing small assembly programs. Below I have written a very basic assembly program. The code typed out is as follows mov ax,0015 mov cx,0023 sub cx,ax mov [120],al mov cl,[120]A nop R is for Register (to jump to a point in memory) The r command turns out to be one of the most frequent commands you will use in DEBUG. It allows you to view the contents of registers and to change their values. It can be used with the following combinations… R – Displays the contents of all the registers R f – Displays the flags register R register_name – Displays the contents of a specific register All three methods are illustrated in the image above T is for Trace (To execute a program step by step) The t command allows us to execute the program step by step. Before we can trace the program we need to point back to the beginning of the program. We do this by typing in r ip, which moves us back to memory point 100. We then type trace which executes the first line of code (line 100) (As shown in the image below starting from the red arrow). You can see from the above image that the register AX now contains 0015 as per our instruction mov ax,0015 You can also see that the IP points to line 0103 which has the MOV CX,0023 command If we type t again it will now execute the second line of the program which moves 23 in the cx register. Again, we can see that the line of code was executed and that the CX register now holds the value of 23. What I would like to highlight now is the section underlined in red. These are the status flags. The ones we are going to look at now are 1st (NV), 4th (PL), 5th (NZ) & 8th (NC) NV means no overflow, the alternate would be OV PL means that the sign of the previous arithmetic operation was Plus, the alternate would be NG (Negative) NZ means that the results of the previous arithmetic operation operation was Not Zero, the alternate would be ZR NC means that No final Carry resulted from the previous arithmetic operation. CY means that there was a final Carry. We could now follow this process of entering the t command until the entire program is executed line by line. G is for Go (To execute a program up to a certain line number) So we have looked at executing a program line by line, which is fine if your program is minuscule BUT totally unpractical if we have any decent sized program. A quicker way to run some lines of code is to use the G command. The ‘g’ command executes a program up to a certain specified point. It can be used in connection with the the reset IP command. You would set your initial point and then run the G command with the line you want to end on. P is for Proceed (Similar to trace but slightly more streamlined) Another command similar to trace is the proceed command. All that the p command does is if it is called and it encounters a CALL, INT or LOOP command it terminates the program execution. In the example below I modified our example program to include an int 20 at the end of it as illustrated in the image below… Then when executing the code when I encountered the int 20 command I typed the P command and the program terminated normally (illustrated below). D is for Dump (or for those more polite Display) So, we have all these assembly lines of code, but if you have ever opened up an exe or com file in a text/hex editor, it looks nothing like assembly code. The D command is a way that we can see what our code looks like in memory (or in a hex editor). If we examined the image above, we can see that Debug is storing our assembly code with each instruction following immediately after the previous one. For instance in memory address 110 we have int and 111 we have 20. If we examine the dump of memory we can see at memory point 110 CD is stored and at memory point 111 20 is stored. U is for Unassemble (or Convert Machine code to Assembly Code) So up to now we have gone through a bunch of commands, but probably one of the most useful is the U command. Let’s say we don’t understand machine code so well and so instead we want to see it in its equivalent assembly code. We can type the U command followed by the start memory point, followed by the end memory point and it will show us the assembly code equivalent of the machine code. E is for a bunch of things… The E command can be used for a bunch of things… One example is to enter data or machine code instructions directly into memory. It can also be used to display the contents of memory locations. I am not going to worry to much about it in this post. N / L / W is for Name, Load & Write So we have written out assembly code in debug, and now we want to save it to disk, or write it as a com file or load it. This is where the N, L & W command come in handy. The n command is used to give a name to the executable program file and is pretty simple to use. The w command is a bit trickier. It saves to disk all the memory between point bx and point cx so you need to specify the bx memory address and the cx memory address for it to write your code. Let’s look at an example illustrated below. You do this by calling the r command followed by the either bx or cx. We can then go to the directory where we were working and will see the new file with the name we specified. The L command is relatively simple. You would first specify the name of the file you would like to load using the N command, and then call the L command. Q is for Quit The last command that I am going to write about in this post is the Q command. Simply put, calling the Q command exits DEBUG. Commands we did not Cover Out of the standard DEBUG commands we covered A, T, G, D, U, E, P, R, N, L & W. The ones we did not cover were H, I & O – I might make mention of these in a later post, but for the basics they are not really needed. Some Useful Resources Please note this post is based on the COS2213 handouts for UNISA A Guide to DEBUG - http://mirror.href.com/thestarman/asm/debug/debug.htm#NT

    Read the article

  • Query on simple C++ threadpool implementation

    - by ticketman
    Stackoverflow has been a tremendous help to me and I'd to give something back to the community. I have been implementing a simple threadpool using the tinythread C++ portable thread library, using what I have learnt from Stackoverflow. I am new to thread programming, so not that comfortable with mutexes, etc. I have a question best asked after presenting the code (which runs quite well under Linux): // ThreadPool.h class ThreadPool { public: ThreadPool(); ~ThreadPool(); // Creates a pool of threads and gets them ready to be used void CreateThreads(int numOfThreads); // Assigns a job to a thread in the pool, but doesn't start the job // Each SubmitJob call will use up one thread of the pool. // This operation can only be undone by calling StartJobs and // then waiting for the jobs to complete. On completion, // new jobs may be submitted. void SubmitJob( void (*workFunc)(void *), void *workData ); // Begins execution of all the jobs in the pool. void StartJobs(); // Waits until all jobs have completed. // The wait will block the caller. // On completion, new jobs may be submitted. void WaitForJobsToComplete(); private: enum typeOfWorkEnum { e_work, e_quit }; class ThreadData { public: bool ready; // thread has been created and is ready for work bool haveWorkToDo; typeOfWorkEnum typeOfWork; // Pointer to the work function each thread has to call. void (*workFunc)(void *); // Pointer to work data void *workData; ThreadData() : ready(false), haveWorkToDo(false) { }; }; struct ThreadArgStruct { ThreadPool *threadPoolInstance; int threadId; }; // Data for each thread ThreadData *m_ThreadData; ThreadPool(ThreadPool const&); // copy ctor hidden ThreadPool& operator=(ThreadPool const&); // assign op. hidden // Static function that provides the function pointer that a thread can call // By including the ThreadPool instance in the void * parameter, // we can use it to access other data and methods in the ThreadPool instance. static void ThreadFuncWrapper(void *arg) { ThreadArgStruct *threadArg = static_cast<ThreadArgStruct *>(arg); threadArg->threadPoolInstance->ThreadFunc(threadArg->threadId); } // The function each thread calls void ThreadFunc( int threadId ); // Called by the thread pool destructor void DestroyThreadPool(); // Total number of threads available // (fixed on creation of thread pool) int m_numOfThreads; int m_NumOfThreadsDoingWork; int m_NumOfThreadsGivenJobs; // List of threads std::vector<tthread::thread *> m_ThreadList; // Condition variable to signal each thread has been created and executing tthread::mutex m_ThreadReady_mutex; tthread::condition_variable m_ThreadReady_condvar; // Condition variable to signal each thread to start work tthread::mutex m_WorkToDo_mutex; tthread::condition_variable m_WorkToDo_condvar; // Condition variable to signal the main thread that // all threads in the pool have completed their work tthread::mutex m_WorkCompleted_mutex; tthread::condition_variable m_WorkCompleted_condvar; }; cpp file: // // ThreadPool.cpp // #include "ThreadPool.h" // This is the thread function for each thread. // All threads remain in this function until // they are asked to quit, which only happens // when terminating the thread pool. void ThreadPool::ThreadFunc( int threadId ) { ThreadData *myThreadData = &m_ThreadData[threadId]; std::cout << "Hello world: Thread " << threadId << std::endl; // Signal that this thread is ready m_ThreadReady_mutex.lock(); myThreadData->ready = true; m_ThreadReady_condvar.notify_one(); // notify the main thread m_ThreadReady_mutex.unlock(); while(true) { //tthread::lock_guard<tthread::mutex> guard(m); m_WorkToDo_mutex.lock(); while(!myThreadData->haveWorkToDo) // check for work to do m_WorkToDo_condvar.wait(m_WorkToDo_mutex); // if no work, wait here myThreadData->haveWorkToDo = false; // need to do this before unlocking the mutex m_WorkToDo_mutex.unlock(); // Do the work switch(myThreadData->typeOfWork) { case e_work: std::cout << "Thread " << threadId << ": Woken with work to do\n"; // Do work myThreadData->workFunc(myThreadData->workData); std::cout << "#Thread " << threadId << ": Work is completed\n"; break; case e_quit: std::cout << "Thread " << threadId << ": Asked to quit\n"; return; // ends the thread } // Now to signal the main thread that my work is completed m_WorkCompleted_mutex.lock(); m_NumOfThreadsDoingWork--; // Unsure if this 'if' would make the program more efficient // if(NumOfThreadsDoingWork == 0) m_WorkCompleted_condvar.notify_one(); // notify the main thread m_WorkCompleted_mutex.unlock(); } } ThreadPool::ThreadPool() { m_numOfThreads = 0; m_NumOfThreadsDoingWork = 0; m_NumOfThreadsGivenJobs = 0; } ThreadPool::~ThreadPool() { if(m_numOfThreads) { DestroyThreadPool(); delete [] m_ThreadData; } } void ThreadPool::CreateThreads(int numOfThreads) { // Check a thread pool has already been created if(m_numOfThreads > 0) return; m_NumOfThreadsGivenJobs = 0; m_NumOfThreadsDoingWork = 0; m_numOfThreads = numOfThreads; m_ThreadData = new ThreadData[m_numOfThreads]; ThreadArgStruct threadArg; for(int i=0; i<m_numOfThreads; ++i) { threadArg.threadId = i; threadArg.threadPoolInstance = this; // Creates the thread and save in a list so we can destroy it later m_ThreadList.push_back( new tthread::thread( ThreadFuncWrapper, (void *)&threadArg ) ); // It takes a little time for a thread to get established. // Best wait until it gets established before creating the next thread. m_ThreadReady_mutex.lock(); while(!m_ThreadData[i].ready) // Check if thread is ready m_ThreadReady_condvar.wait(m_ThreadReady_mutex); // If not, wait here m_ThreadReady_mutex.unlock(); } } // Adds a job to the batch, but doesn't start the job void ThreadPool::SubmitJob(void (*workFunc)(void *), void *workData) { // Check that the thread pool has been created if(!m_numOfThreads) return; if(m_NumOfThreadsGivenJobs >= m_numOfThreads) return; m_ThreadData[m_NumOfThreadsGivenJobs].workFunc = workFunc; m_ThreadData[m_NumOfThreadsGivenJobs].workData = workData; std::cout << "Submitted job " << m_NumOfThreadsGivenJobs << std::endl; m_NumOfThreadsGivenJobs++; } void ThreadPool::StartJobs() { // Check that the thread pool has been created // and some jobs have been assigned if(!m_numOfThreads || !m_NumOfThreadsGivenJobs) return; // Set 'haveworkToDo' flag for all threads m_WorkToDo_mutex.lock(); for(int i=0; i<m_NumOfThreadsGivenJobs; ++i) m_ThreadData[i].haveWorkToDo = true; m_NumOfThreadsDoingWork = m_NumOfThreadsGivenJobs; // Reset this counter so we can resubmit jobs later m_NumOfThreadsGivenJobs = 0; // Notify all threads they have work to do m_WorkToDo_condvar.notify_all(); m_WorkToDo_mutex.unlock(); } void ThreadPool::WaitForJobsToComplete() { // Check that a thread pool has been created if(!m_numOfThreads) return; m_WorkCompleted_mutex.lock(); while(m_NumOfThreadsDoingWork > 0) // Check if all threads have completed their work m_WorkCompleted_condvar.wait(m_WorkCompleted_mutex); // If not, wait here m_WorkCompleted_mutex.unlock(); } void ThreadPool::DestroyThreadPool() { std::cout << "Ask threads to quit\n"; m_WorkToDo_mutex.lock(); for(int i=0; i<m_numOfThreads; ++i) { m_ThreadData[i].haveWorkToDo = true; m_ThreadData[i].typeOfWork = e_quit; } m_WorkToDo_condvar.notify_all(); m_WorkToDo_mutex.unlock(); // As each thread terminates, catch them here for(int i=0; i<m_numOfThreads; ++i) { tthread::thread *t = m_ThreadList[i]; // Wait for thread to complete t->join(); } m_numOfThreads = 0; } Example of usage: (this calculates pi-squared/6) struct CalculationDataStruct { int inputVal; double outputVal; }; void LongCalculation( void *theSums ) { CalculationDataStruct *sums = (CalculationDataStruct *)theSums; int terms = sums->inputVal; double sum; for(int i=1; i<terms; i++) sum += 1.0/( double(i)*double(i) ); sums->outputVal = sum; } int main(int argc, char** argv) { int numThreads = 10; // Create pool ThreadPool threadPool; threadPool.CreateThreads(numThreads); // Create thread workspace CalculationDataStruct sums[numThreads]; // Set up jobs for(int i=0; i<numThreads; i++) { sums[i].inputVal = 3000*(i+1); threadPool.SubmitJob(LongCalculation, &sums[i]); } // Run the jobs threadPool.StartJobs(); threadPool.WaitForJobsToComplete(); // Print results for(int i=0; i<numThreads; i++) std::cout << "Sum of " << sums[i].inputVal << " terms is " << sums[i].outputVal << std::endl; return 0; } Question: In the ThreadPool::ThreadFunc method, would better performance be obtained if the following if statement if(NumOfThreadsDoingWork == 0) was included? Also, I'd be grateful of criticisms and ways to improve the code. At the same time, I hope the code is of use to others.

    Read the article

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