Getting Started with multithreading

Source: Internet
Author: User
Tags mutex set time ticket

HANDLE CreateThread (lpsecurity_attributes lpthreadattributes,//SD: Thread-safe-related properties, normally nullsize_t Dwstacksize,//initialstacksize: The size of the initialization stack for the new thread, which can be set to 0Lpthread_start_routine Lpstartaddress,//threadfunction: A callback function that is executed by a thread, also known as a thread functionLPVOID Lpparameter,//threadargument: Arguments passed into the thread function, null if no arguments are passedDWORD dwCreationFlags,//creationoption: Controlling thread-created flagsLpdword Lpthreadid//threadidentifier: Outgoing parameter, which is used to obtain the thread ID, or NULL if the thread ID is not returned    )/*lpthreadattributes: A pointer to the SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by the quilt process, or NULL to indicate that the returned handle cannot be inherited by the quilt process. Dwstacksize: Sets the size of the initial stack, in bytes, and if 0, the default is to use the same stack space size as the thread that called the function. In any case, Windows dynamically extends the size of the stack as needed. Lpstartaddress: A pointer to a thread function that has no restriction on the function name, but must be declared in the following form: The DWORD WINAPI function name (LPVOID lpparam) is malformed and cannot be called successfully. Lpparameter: A parameter passed to a thread function, which is a pointer to a struct, null if no arguments are passed. dwCreationFlags: The flags that control thread creation are as follows: (1) create_suspended (0x00000004): Creates a suspended thread (ready state) until the thread is awakened (2) 0: Indicates that it is activated immediately after creation. (3) Stack_size_param_is_a_reservation (0x00010000): The dwstacksize parameter specifies the size of the initial hold stack, if Stack_size_param_is_a_ The reservation flag is unspecified, dwstacksize will be set to the system reserved value Lpthreadid: Save the ID return value of the new thread: The function succeeds, returns the thread handle, otherwise returns NULL. If the thread creation fails, you can get the error message through the GetLastError function. */BOOL WINAPI CloseHandle (HANDLE hobject); //closes an open object handle/*This function can be used to close the created thread handle, return TRUE if the function executes successfully (not 0), or False (0) if failed, and call GetLastError if execution fails. The function obtains the error message. */
 handle WINAPI CreateMutex (lpsecurity_attributes lpmutexattributes,  
   
    // 
     thread-safe-related properties, normally null  BOOL binitial    Owner, 
    // 
     If the current thread that created the mutex has ownership of the mutex  LPCTSTR lpname 
    // 
    mutex name Called  
     /*  mutexattributes: is also a structure that represents security, the same as lpthreadattributes function in CreateThread, Indicates whether the returned handle can be inherited by the quilt process, or NULL to indicate that the returned handle cannot be inherited by the quilt process. Binitialowner: Indicates whether the current thread that created the mutex has ownership of the mutex and, if true, specifies that the current creation thread is the owner of the mutex object, and that the other thread accesses the name that needs to be releasemutexlpname:mutex first  */ 
   
 dword WINAPI WaitForSingleObject (HANDLE hhandle,  //     The handle of the lock to get  DWORD dwmilliseconds //  timeout interval  /*  waitforsingleobject: Waits for a specified object (such as a mutex object) until the object is in a non-occupied state (such as a mutex object being freed) or out of a set interval. In addition, there is a function similar to it waitformultipleobjects, which is to wait for one or all of the specified objects until all objects are in a non-occupied state, or beyond the set time interval. Hhandle: The handle of the specified object to wait for. Dwmilliseconds: timeout interval, in milliseconds, if dwmilliseconds is not 0, wait until dwmilliseconds time interval is exhausted or the object becomes non-occupied, if dwmilliseconds The infinite represents an infinite wait until the waiting object is in a non-occupied state.  */ 
BOOL WINAPI ReleaseMutex (HANDLE hmutex); // Description: Frees the owning mutex lock object, Hmutex as the freed mutex handle

The above is a more commonly used Windows system provides us with the relevant API, we can use them for multithreaded programming

Example 1:

#include <iostream>#include<windows.h>using namespacestd; HANDLE Hmutex= NULL;//Mutex Amount//Thread FunctionsDWORD WINAPI Fun (lpvoid lpparamter) { for(inti =0; I <Ten; i++)    {        //request a mutex lockWaitForSingleObject (Hmutex, INFINITE); cout<<"A Thread Fun display!"<<Endl; Sleep ( -); //Release Mutex lockReleaseMutex (Hmutex); }    return 0L;//indicates that the return is a long type of 0}intMain () {//Create a child threadHANDLE hthread = CreateThread (NULL,0, Fun, NULL,0, NULL); Hmutex= CreateMutex (NULL, FALSE," Screen"); //Close ThreadCloseHandle (hthread); //execution path of the main thread     for(inti =0; I <Ten; i++)    {        //request for a mutex lockWaitForSingleObject (Hmutex,infinite); cout<<"Main Thread display!"<<Endl; Sleep ( -); //Release Mutex lockReleaseMutex (Hmutex); }    return 0;}

#include <windows.h>#include<iostream.h>using namespaceStd;dword WINAPI fun1proc (LPVOID lpparameter);//Thread DataDWORD WINAPI Fun2proc (LPVOID lpparameter);//Thread Dataintindex=0;inttickets=Ten; HANDLE Hmutex;voidMain () {HANDLE hThread1;    HANDLE hThread2; //Creating ThreadsHThread1=createthread (NULL,0, Fun1proc,null,0, NULL); HThread2=createthread (NULL,0, Fun2proc,null,0, NULL);    CloseHandle (HTHREAD1);    CloseHandle (HTHREAD2); //creating a Mutex objectHmutex=createmutex (Null,true,"Tickets"); if(Hmutex) {if(error_already_exists==GetLastError ()) {cout<<"Only one instance can run!"<<Endl; return 0;    }} WaitForSingleObject (Hmutex,infinite);    ReleaseMutex (Hmutex);        ReleaseMutex (Hmutex); Sleep (4000);}//entry function for thread 1DWORD WINAPI Fun1proc (LPVOID lpparameter)//Thread Data{     while(true) {ReleaseMutex (Hmutex);        WaitForSingleObject (Hmutex,infinite); if(tickets>0) {Sleep (1); cout<<"Thread1 Sell ticket:"<<tickets--<<Endl; }        Else             Break;    ReleaseMutex (Hmutex); }    return 0;}//entry function for thread 2DWORD WINAPI Fun2proc (LPVOID lpparameter)//Thread Data{     while(true) {ReleaseMutex (Hmutex);        WaitForSingleObject (Hmutex,infinite); if(tickets>0) {Sleep (1); cout<<"thread2 Sell ticket:"<<tickets--<<Endl; }        Else             Break;    ReleaseMutex (Hmutex); }        return 0;}

Getting Started with multithreading

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.