C/c++-createthread related APIs

Source: Internet
Author: User
Tags mutex

To use a mutex object:

#include <windows.h> #include <iostream> #define ThreadCount 6HANDLE Ghmutex;dword WINAPI runthreadfunction    (LPVOID lpparam); int main (void) {HANDLE athread[threadcount];    DWORD ThreadID;    Create a mutex with no owner Ghmutex = CreateMutex (null, FALSE, NULL);        if (Ghmutex = = NULL) {std::cout << "CreateMutex error:" << GetLastError () << Std::endl;    return 1;                     } for (int i = 0; i < ThreadCount; i++) {Athread[i] = CreateThread (NULL, 0, (lpthread_start_routine) runthreadfunction, NULL, 0        , &threadid);  if (athread[i] = = nullptr) {std::cout << CreateThread error: "<< GetLastError () <<            Std::endl;        return 1;    }}//wait until all threads are terminated waitformultipleobjects (ThreadCount, Athread, TRUE, INFINITE); for (int i = 0; i < ThreadcoUNT;    i++) CloseHandle (Athread[i]);    Closes all thread handles and frees memory CloseHandle (Ghmutex); return 0;}    DWORD WINAPI runthreadfunction (lpvoid lpparam) {unreferenced_parameter (Lpparam);    DWORD Dwwaitresult; for (int i = 0; i < 5; i++) {//Get exclusive rights Dwwaitresult = WaitForSingleObject (Ghmutex, Infin        ITE);  Switch (dwwaitresult) {case Wait_object_0:try {std::cout << i                << Thread << getcurrentthreadid () << "is run ..." << Std::endl; } catch (...) {if (! ReleaseMutex (Ghmutex))//release Mutex {std::cout << "ReleaseMutex error" &lt                    ;< Std::endl;            }} break;        The thread is in an indeterminate state case Wait_abandoned:return FALSE; }} return TRUE;

If you remove the mutex you can see the output is very confusing ... The reason is also that the output of std::cout is spliced. It would be nice to output with printf, but the output I could be confusing.

Such as:

Operation Result of Lock:

Here's an example of creating a thread that you see on MSDN, and if you want to pass other types of arguments without a type conversion warning, you can do this:

#include <windows.h> #include <tchar.h> #include <strsafe.h> #define Max_threads 3#define buf_size 255DWORD WINAPI mythreadfunction (lpvoid lpparam); void ErrorHandler (LPTSTR lpszfunction); typedef struct MYDATA {int V    Al1; int val2;}    MYDATA, *pmydata;int _tmain () {pmydata pdataarray[max_threads];    DWORD Dwthreadidarray[max_threads];    HANDLE Hthreadarray[max_threads]; for (int i=0; i<max_threads; i++) {Pdataarray[i] = (pmydata) HeapAlloc (GetProcessHeap (), Heap_zero_memory,        sizeof (MYDATA));        if (pdataarray[i] = = NULL) {exitprocess (2);        } pdataarray[i]->val1 = i;        Pdataarray[i]->val2 = i+100;            Hthreadarray[i] = CreateThread (NULL, 0, MyThreadFunction, Pdataarray[i],        0, &dwthreadidarray[i]);           if (hthreadarray[i] = = NULL) {ErrorHandler ((LPTSTR) TEXT ("CreateThread"));   ExitProcess (3);     }} waitformultipleobjects (Max_threads, Hthreadarray, TRUE, INFINITE);        for (int i=0; i<max_threads; i++) {CloseHandle (hthreadarray[i]);            if (pdataarray[i]! = NULL) {HeapFree (GetProcessHeap (), 0, pdataarray[i]);        Pdataarray[i] = NULL; }} return 0;}    DWORD WINAPI mythreadfunction (lpvoid lpparam) {HANDLE hstdout;    Pmydata Pdataarray;    TCHAR Msgbuf[buf_size];    size_t Cchstringsize;    DWORD Dwchars;    hStdOut = GetStdHandle (Std_output_handle);    if (hStdOut = = Invalid_handle_value) return 1;    Pdataarray = (pmydata) Lpparam;    stringcchprintf (Msgbuf, Buf_size, TEXT ("Parameters =%d,%d\n"), Pdataarray->val1, Pdataarray->val2);    Stringcchlength (Msgbuf, Buf_size, &cchstringsize);    Writeconsole (hStdOut, Msgbuf, (DWORD) cchstringsize, &dwchars, NULL); return 0;}    void ErrorHandler (LPTSTR lpszfunction) {lpvoid lpmsgbuf;    LPVOID Lpdisplaybuf;    DWORD DW = GetLastError (); FormAtmessage (Format_message_allocate_buffer |        Format_message_from_system | Format_message_ignore_inserts, NULL, DW, Makelangid (Lang_neutral, Sublang_default), (LPTSTR) &    Amp;lpmsgbuf, 0, NULL); Lpdisplaybuf = (LPVOID) LocalAlloc (Lmem_zeroinit, (Lstrlen (LPCTSTR) lpmsgbuf) + lstrlen ((LPCTSTR) lpszFunction) + +) * s    Izeof (TCHAR)); stringcchprintf ((LPTSTR) lpdisplaybuf, Localsize (lpdisplaybuf)/sizeof (TCHAR), TEXT ("%s failed with error%d:%s"),    Lpszfunction, DW, LPMSGBUF);    MessageBox (NULL, (LPCTSTR) lpdisplaybuf, TEXT ("Error"), MB_OK);    LocalFree (LPMSGBUF); LocalFree (LPDISPLAYBUF);}

The key part is the use of structural type.

C/c++-createthread related APIs

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.