Windows Thread Pool + use Windows built-in Thread Pool

Source: Internet
Author: User

Come from: http://www.fuzhijie.me /? P = 65
I always wanted to understand what the I/O completion port for Windows is. Every time this word appears in front of me, it is always accompanied by flowers and praise, therefore, I classify things I have never understood as a mysterious one. I have been reading windows core programming for the past two days and have learned many things. But like other English classics, the Chinese version often makes me feel like Yun, I do not like examples in books that are written in C ++ and have graphic interfaces. This hinders beginners from understanding the nature of the problem. Not everyone is familiar with graphic interface programming in windows, in Windows, there are not only a large number of APIS, but also many API parameters. If it is just a simple type, many parameters will be complex structures. In contrast, UNIX system calls are much simpler. I plan to step by step. I first learned how to use the thread pool that comes with windows. This is a good implementation. Linux does not provide the equivalent.

In msdn, only one instance is provided for the use of the thread pool, and the related code is poor on the Internet. I can only treat this example as a treasure, and I have studied it well and removed some vertices, add comments as reading notes.

In Windows core programming, we classify the things that the thread pool allows us to do as follows:
Scenario 1: Call a function Asynchronously
Scenario 2: Call a function at intervals
Scenario 3: Call a function when the kernel object is triggered
Scenario 4: Call a function when the asynchronous I/O request is complete.

The example in msdn demonstrates the first three scenarios. The callback function signatures in these three scenarios are different. The original program did not set a callback function for the cleanup group. I wrote a cleanup callback function and simply printed the thread Number of the running code.

/// Thread pool wait callback function template ///// note the signatures of these three callback functions. None of them return the voidcallbackmywaitcallback (ptp_callback_instance instance, pvoid parameter, ptp_wait wait, tp_wait_result waitresult) {printf ("% u in mywaitcallback \ n", getcurrentthreadid ();} // thread pool timer callback function template // voidcallbackmytimercallback (ptp_callback_instance instance, pvoid parameter, ptp_timer timer) {PR INTF ("(% u) in mytimercallback \ n", getcurrentthreadid ();} // This is the thread pool work callback function. // The callback demonstrates correct behavior when changing the // state of the thread inside the callback function. /// any changes to the thread state must be restored to original // before exiting the callback routine. // voidcallbackmyworkcallback (ptp_callback_instance instance, pvoid par Ameter, ptp_work work) {printf ("(% u) in myworkcallback \ n", getcurrentthreadid ();} voidcallbackmycleanupcallback (pvoid pvobjectcontext, pvoid pvcleanupcontext) {printf ("(% u) in mycleanupcallback \ n", getcurrentthreadid ();} voiddemocleanuppersistentworktimer () {bool Bret = false; ptp_work work = NULL; ptp_timer timer = NULL; ptp_pool pool = NULL; tp_callback_environ callbackenviron; ptp_cleanup_group Cl Eanupgroup = NULL; filetime fileduetime; ularge_integer ulduetime; uint rollback = 0; printf ("(% u) in democleanuppersistentworktimer \ n", getcurrentthreadid (); // Initialization is important, otherwise, an error will occur when running to createthreadpoolwork. // you can check the content of the tp_callback_environ struct in debug mode initializethreadpoolenvironment (& callbackenviron); // create a custom, dedicated thread pool // pool = createthreadpool (null); If (null = pool) {_ tprintf (_ T ("createthre Adpool failed. lasterror: % u \ n "), getlasterror (); goto main_cleanup;} rollback = 1; // pool creation succeeded // The thread pool is made persistent simply by setting // both the minimum and maximum threads to 1. //// set the maximum and minimum values to 1. When several work items are submitted, all work items are completed by this thread. // if multiple threads can be enabled, we can see several threads are working together to complete these work items setthreadpoolthreadmaximum (pool, 1); Bret = setthreadpoolthreadminimum (pool, 4); If (false = BRET) {_ tprintf (_ T ("setthreadpoolthreadminimum failed. lasterror: % u \ n "), getlasterror (); goto main_cleanup;} // create a cleanup group for this thread pool // cleanupgroup = createthreadpoolcleanupgroup (); if (null = cleanupgroup) {_ tprintf (_ T ("createthreadpoolcleanupgroup failed. lasterror: % u \ n "), getlasterror (); goto main_cleanup;} rollback = 2; // cleanup group creation succeeded // associate the callback Environment with our thread pool // setthreadpoolcallbackpool (& callbackenviron, pool); // associate the cleanup group with our thread pool // reset (& callbackenviron, cleanupgroup, & mycleanupcallback ); /// create work with the callback environment // The thread pool used is included in the callbackenviron parameter. // If null is passed here, A default thread pool will be used: Work = createthreadpoolwork (ptp_work_callback) myworkcallback, null, & Ca Llbackenviron); If (null = work) {_ tprintf (_ T ("createthreadpoolwork failed. lasterror: % u \ n "), getlasterror (); goto main_cleanup;} rollback = 3; // creation of work succeeded // submit the work to the pool. because this was a pre-allocated // work item (using createthreadpoolwork), it is guaranteed // to execute /// you can try to submit several more work items, submitthreadpoolwork (work ); submitthreadpoolwork (work); submitthreadpoo Lwork (work); submitthreadpoolwork (work); // create a timer with the same callback environment // timer = callback (ptp_timer_callback) mytimercallback, null, & callbackenviron ); if (null = timer) {_ tprintf (_ T ("createthreadpooltimer failed. lasterror: % u \ n "), getlasterror (); goto main_cleanup;} rollback = 4; // timer creation succeeded /// set the timer to fire in one second /// if it is a positive value, it indicates Absolute Time, calculated from January 1, January 1, 1600. The unit is nanoseconds. // if the value is negative, the relative time is displayed. The unit is microsecond. // The unit is different in two cases. Ulduetime. quadpart = (Longlong)-(100000000); fileduetime. dwhighdatetime = ulduetime. highpart; fileduetime. dwlowdatetime = ulduetime. lowpart; // The timer only triggers one setthreadpooltimer (timer, & fileduetime, 0, 0 ); /// delay for the timer to be fired /// wait for the thread in the thread pool to finish the timer. Note that the sleep value here is greater than the value triggered by the timer above, otherwise, the result is invisible. Sleep (15000); // wait for all callbacks to finish. // closethreadpoolcleanupgroupmembers also callthe cleanup // functions for all the individual objects in the specified // cleanup group. //// at this time, the main thread will call mycleanupcallback twice. I still have no idea how to use closethreadpoolcleanupgroupmembers (cleanupgroup, false, null ); /// already cleaned up the work item with the // closethreadpoolcleanupgroupmembers, so set rollback to 2. // rollback = 2; goto main_cleanup; main_cleanup: // clean up any individual pieces manually // notice the fall through structure of the switch. // clean up in reverse order. // switch (rollback) {Case 4: Case 3: // clean up the cleanup group membersclosethreadpoolcleanupgroupmembers (cleanupgroup, false, null); Case 2: // clean up the cleanup groupclosethreadpoolcleanupgroup (cleanupgroup); Case 1: // clean up the poolclosethreadpool (pool); default: break;} return;} voiddemonewregisterwait () {ptp_wait wait = NULL; handle hevent = NULL; uint I = 0; uint rollback = 0; printf ("(% u) in demonewregisterwait \ n", getcurrentthreadid ()); /// create an auto-Reset event // hevent = createevent (null, false, false, null); If (null = hevent) {// error handlingreturn ;} rollback = 1; // createevent succeeded wait = createthreadpoolwait (ptp_wait_callback) mywaitcallback, null, null); If (null = wait) {_ tprintf (_ T ("failed. lasterror: % u \ n "), getlasterror (); goto new_wait_cleanup;} rollback = 2; // createthreadpoolwait succeeded // need to re-register the event with the wait object // each time before signaling the event to trigger the // wait callback // for (I = 0; I <5; I ++) {setthreadpoolwait (wait, hevent, null); // set the service to the trigger state setevent (hevent ); /// delay for the waiter thread to act if necessary // sleep (500 ); /// block here until the callback function is done executing // wait for the callback function to run waitforthreadpoolwaitcallbacks (wait, false);} new_wait_cleanup: Switch (rollback) {Case 2: // unregister the wait by setting the event to nullsetthreadpoolwait (wait, null, null); // close waitclosethreadpoolwait (wait); Case 1: // close eventclosehandle (hevent); default: break;} return;} int main () {democleanuppersistentworktimer (); demonewregisterwait (); Return 0 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.